定时执行策略的应用
(一)使用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>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</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>