Spring 简单定时器

来源:互联网 发布:linux配置dhcp服务器 编辑:程序博客网 时间:2024/04/29 06:18

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

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也可以 可以看到定时器正常执行了