Spring 简单定时器

本文介绍了一个使用Spring框架实现的简单定时任务案例。首先定义了一个执行定时任务的Test类,并通过Spring配置文件设置定时任务参数,如执行周期和首次执行延迟等。最后验证了定时任务的正常运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个类在测试的时候显示过时了。 不过用来学习一下倒也不错。

1. 定义一个简单的test类 这个类是用来执行定时执行的代码的。

import javax.faces.application.Application;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PostBeanFactory implements BeanFactoryPostProcessor {

 public void postProcessBeanFactory(
   ConfigurableListableBeanFactory beanFactory) throws BeansException {
  // TODO Auto-generated method stub
  String[]names=beanFactory.getBeanDefinitionNames();
  for (String string : names) {
   System.out.println(string);
  }
 }
 public static void main(String[] args) {
  ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
  UserInfo info=(UserInfo)app.getBean("userinfo");
  info.printinfo();
 }

}

2. 剩下的工作就是spring的配置文件了,为了便于管理,应建立一个单独的文件

<bean id="testtask" class="com.test.TestTask"></bean>//刚才那个测试类
 <bean id="testscheduled" class="org.springframework.scheduling.timer.ScheduledTimerTask">//定时任务类 spring自带
  <property name="timerTask">//将刚才那个实现了timertask的类注入进去
   <ref bean="testtask"/>
  </property>
  <property name="period" value="2000"></property>//定时时间
  <property name="delay" value="1000"></property>//第一次延迟执行时间
 </bean>
 <bean id="timerfactory" class="org.springframework.scheduling.timer.TimerFactoryBean">//将这个定时任务类注入 看起来可以创建多个的样子
  <property name="scheduledTimerTasks">
   <ref bean="testscheduled"/>
  </property>
 </bean>

3. 启动服务器也可以 执行main也可以 可以看到定时器正常执行了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值