前几天使用到了任务调度框架Quartz,并且和spring进行整合使用,现在在这里做下记录:
1. 首先导入Quartz的jar包,可以去官网下载,若是使用maven的话就直接使用maven导入:
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>1.8.6</version> <!-- 最新版本是1.8.6 --> </dependency>2. 导入spring的包:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
3. 接下来就是实现任务类 ,有两种方式:
3.1 第一种方式:
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中的配置文件代码:
<!-- 第一种方式实现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 第二种方式:
package com.hqhp.quartz; public class ExampleBusinessObject { // properties and collaborators public void doIt() { // do the actual work System.out.println("do it ..."); } }相应的sping的配置文件:
<!-- 第二种方式实现JobDetail --> <bean id="exampleBusinessObject" class="com.hqhp.quartz.ExampleBusinessObject" /> <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="exampleBusinessObject" /> <property name="targetMethod" value="doIt" /> </bean>4. 开始配置触发器,触发器也有两种方式,和任务类的方式对应:
4.1 第一种方式
<!-- 触发器的一种方式 --> <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> <!-- see the example of method invoking job above --> <property name="jobDetail" ref="jobQuartzDetail" /> <!-- 5 seconds --> <property name="startDelay" value="5000" /> <!-- repeat every 10 seconds --> <property name="repeatInterval" value="10000" /> </bean>4 .2 第二种方式:
<!-- 触发器第二种方式 --> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="jobDetail" /> <property name="cronExpression" value="0 29 13 * * ?" /> <!-- 每天13:29会执行一次配置的任务 --> </bean>5. 最后就是把触发器加入到任务列表中:
<bean id='testScheduler' class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="simpleTrigger" />
<ref bean="cronTrigger" />
</list>
</property>
</bean>