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