集成TimerTask 容易造成对业务代码的侵入,这种方式更符合spring的思想。
http://caterpillar.onlyfun.net/GossipCN/SpringGossip/MethodInvokingTimerTaskFactoryBean.html
使 用Spring时,您并不一定要继承TimerTask来定义一个任务,Spring提供org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean,可以让您直接指定呼叫某个物件的方法,例如可以改写一下 使用TimerTask 中的DemoTask类别,这次不用继承TimerTask类别:
package onlyfun.caterpillar;public class DemoTask { public void execute() { System.out.println("Task is executed."); }}
接着只要在Bean定义档中使用MethodInvokingTimerTaskFactoryBean即可,例如:
<?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的实例以呼叫目标物件上的指定方法。 |