使 用 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的实例以呼叫目标物件上的指定方法。