使用OpenSymphony Quartz 调度器
23.2. 使用OpenSymphony Quartz 调度器
Quartz使用Trigger, Job以及JobDetail等对象来进行各种类型的任务调度。关于Quartz的基本概念,请参阅http://www.opensymphony.com/quartz。为了让基于Spring的应用程序方便使用,Spring提供了一些类来简化uartz的用法。
23.2.1. 使用JobDetailBean
JobDetail 对象保存运行一个任务所需的全部信息。Spring提供一个叫作JobDetailBean的类让JobDetail能对一些有意义的初始值进行初始化。让我们来看个例子:
<bean name="exampleJob" value="example.ExampleJob" /> <property name="jobDataAsMap"> <map> <entry key="timeout" value="5" /> </map> </property></bean>
package example;public class ExampleJob extends QuartzJobBean { private int timeout; /** * Setter called after the ExampleJob is instantiated * with the value from the JobDetailBean (5) */ public void setTimeout(int timeout) { this.timeout = timeout; } protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException { // do the actual work }}<bean id="jobDetail" ref="exampleBusinessObject" /> <property name="targetMethod" value="doIt" /></bean>
public class ExampleBusinessObject { // properties and collaborators public void doIt() { // do the actual work }}<bean id="exampleBusinessObject" name="code"><bean id="jobDetail" ref="exampleBusinessObject" /> <property name="targetMethod" value="doIt" /> <property name="concurrent" value="false" /></bean><bean id="simpleTrigger" ref="jobDetail" /> <!-- 10 seconds --> <property name="startDelay" value="10000" /> <!-- repeat every 50 seconds --> <property name="repeatInterval" value="50000" /></bean><bean id="cronTrigger" ref="exampleJob" /> <!-- run every morning at 6 AM --> <property name="cronExpression" value="0 0 6 * * ?" /></bean>
<bean /> <ref bean="simpleTrigger" /> </list> </property></bean>