?
本文檔使用 php中文網(wǎng)手冊 發(fā)布
另外一個(gè)調(diào)度任務(wù)的途徑是使用JDK Timer對象。你可以創(chuàng)建定制的timer或者調(diào)用某些方法的timer。包裝timers的工作由TimerFactoryBean
完成。
你可以使用TimerTask
創(chuàng)建定制的timer tasks,類似于Quartz中的jobs:
public class CheckEmailAddresses extends TimerTask {
private List emailAddresses;
public void setEmailAddresses(List emailAddresses) {
this.emailAddresses = emailAddresses;
}
public void run() {
// iterate over all email addresses and archive them
}
}
包裝它很簡單:
<bean id="checkEmail" class="examples.CheckEmailAddress"> <property name="emailAddresses"> <list> <value>test@springframework.org</value> <value>foo@bar.com</value> <value>john@doe.net</value> </list> </property> </bean> <bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> <!-- wait 10 seconds before starting repeated execution --> <property name="delay" value="10000" /> <!-- run every 50 seconds --> <property name="period" value="50000" /> <property name="timerTask" ref="checkEmail" /> </bean>
注意若要讓任務(wù)只運(yùn)行一次,你可以把period
屬性設(shè)置為0(或者負(fù)值)。
和對Quartz的支持類似,對Timer
的支持也包含一個(gè)組件,可以讓你周期性的調(diào)用某個(gè)方法:
<bean id="doIt" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"> <property name="targetObject" ref="exampleBusinessObject" /> <property name="targetMethod" value="doIt" /> </bean>
以上的例子會調(diào)用exampleBusinessObject
對象的doIt
方法。(見下):
public class BusinessObject { // properties and collaborators public void doIt() { // do the actual work } }
將上例中ScheduledTimerTask
的timerTask
引用修改為doIt
,bean將會用一個(gè)固定的周期來調(diào)用doIt
方法。
TimerFactoryBean
類和Quartz的SchedulerFactoryBean
類有些類似,它們是為同樣的目的而設(shè)計(jì)的:設(shè)置確切的任務(wù)計(jì)劃。TimerFactoryBean
對一個(gè)Timer進(jìn)行配置,設(shè)置其引用的任務(wù)的周期。你可以指定是否使用背景線程。
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<!-- see the example above -->
<ref bean="scheduledTask" />
</list>
</property>
</bean>