前几天使用到了任务调度框架Quartz,并且和spring进行整合使用,现在在这里做下记录:
1. 首先导入Quartz的jar包,可以去官网下载,若是使用maven的话就直接使用maven导入:
[html]
<span style="white-space:pre"> </span><dependency>
<span style="white-space:pre"> </span><groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.6</version> <!-- 最新版本是1.8.6 -->
</dependency>
2. 导入spring的包:
[html]
<span style="white-space:pre"> </span><dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
3. 接下来就是实现任务类 ,有两种方式:
3.1 第一种方式:
[java]
package com.hqhp.quartz;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class JobQuartz extends QuartzJobBean {
private int timeout;
public JobQuartz(){
}
/**
* 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
System.out.println("quartz test success…"+timeout);
}
}
相应的spring中的配置文件代码:
[html]
<!-- 第一种方式实现JobDetail -->
<bean name="jobQuartzDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.hqhp.quartz.JobQuartz" />
<property name="Durability" value="true" />
<property name="jobDataAsMap">
<map>
<entry key="timeout" value="5" />
</map>
</property>
</bean>
3.2 第二种方式:
[java]
package com.hqhp.quartz;
public class ExampleBusinessObject {
// properties and collaborators
public void doIt() {
// do the actual work
System.out.println("do it …");
}
}