定時執行策略的應用
(一)使用Quartz
Quartz是opensymphony組織的一個框架,請參見www.opensymphony.com/quartz
如果要使用quartz來實現定時執行策略,首先需要創建一個任務。即寫一個擴展QuartzJobBean的Bean
例如:
public class XmlPublishJob extends QuartzJobBean {
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
//do something;
}
}
然後在spring的config文件中對定時執行策略進行定義
<!-- 增加定時執行發佈程序的策略 By Roy 2005-11-11 -->
<!--定義任務-->
<bean name="publishJob" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<value>com.mywap.common.publish.XmlPublishJob</value>
</property>
<property name="jobDataAsMap">
<map>
<entry key="timeout"><value>50</value></entry>
<entry key="pageinfoService"><ref bean="pageinfoService"></ref></entry>
<entry key="rowsinfoService"><ref bean="rowsinfoService"></ref></entry>
<entry key="columninfoService"><ref bean="columninfoService"></ref></entry>
</map>
</property>
</bean>
<!--設置觸發器-->
<bean id="publishTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail">
<!-- see the example of method invoking job above -->
<ref bean="publishJob"/>
</property>
<property name="startDelay">
<!-- 10 seconds -->
<value>1000</value>
</property>
<property name="repeatInterval">
<!-- repeat every 50 seconds -->
<value>5000</value>
</property>
</bean>
<!--進行觸發-->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref local="publishTrigger"/>
</list>
</property>
</bean>
(二)使用JDK Timer
首先需要創建定製的timers
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
}
}
然後在spring的配置文件中配置
<bean id="checkEmail" class="examples.CheckEmailAddress">
<property name="emailAddresses">
<list>
<value>[email protected]</value>
<value>[email protected]</value>
<value>[email protected]</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</value>
</property>
<!-- run every 50 seconds -->
<property name="period">
<value>50000</value>
</property>
<property name="timerTask">
<ref local="checkEmail"/>
</property>
</bean>
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<!-- see the example above -->
<ref local="scheduledTask"/>
</list>
</property>
</bean>