集成TimerTask 容易造成对业务代码的侵入,这种方式更符合spring的思想。
http://caterpillar.onlyfun.net/GossipCN/SpringGossip/MethodInvokingTimerTaskFactoryBean.html
使 用Spring 时,您并不一定要继承TimerTask 来定义一个任务,Spring 提供 org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean , 可以让您直接指定呼叫某个物件的方法,例如可以改写一下 使用 TimerTask 中的DemoTask 类别,这次不用继承TimerTask 类别:
- DemoTask.java
package onlyfun.caterpillar;
public class DemoTask {
public void execute() {
System.out.println("Task is executed.");
}
}
接着只要在Bean 定义档中使用MethodInvokingTimerTaskFactoryBean 即可,例如:
- beans-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="demoTask" class="onlyfun.caterpillar.DemoTask"/> <bean id="timerTaskBean" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"> <property name="targetObject"> <ref bean="demoTask"/> </property> <property name="targetMethod"> <value>execute</value> </property> </bean> <bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <property name="timerTask"> <ref bean="timerTaskBean"/> </property> <property name="period"> <value>5000</value> </property> <property name="delay"> <value>1000</value> </property> </bean> <bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <ref bean="scheduledTimerTask"/> </list> </property> </bean> </beans>
执行时可以直接使用 使用 TimerTask 中的TimerTaskDemo 类别,在底层,MethodInvokingTimerTaskFactoryBean 会自动建立TimerTask 的实例以呼叫目标物件上的指定方法。