在项目中有进可能会用到定进服务,一些简单的定时服务可以用java中的timer,timertask来实现,但如果有比较复杂的触发条件就是用到opensynphony的开源定时服务包quartz。spring为quartz提供了良好的支持。spring中相关的定时服务的包在org.springframework.scheduling.quartz.*中。
在quartz中有两种方式来实现定时服务,一种方法是实现QuartzJobBean,另一种方法是写一个服务类,用spring提供的类型进行包装成quartzjobbean(貌似adapter).
先用第一种方法来写一个示
package quartz1;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class LogJob extends QuartzJobBean ...{
private int timeout;

public int getTimeout() ...{
return timeout;
}

public void setTimeout(int timeout) ...{
this.timeout = timeout;
}
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException ...{
System.out.println("quartz do......");
}
}
这个服务类写好后,再配置一个触发器,就能运行了。
spring中的配置如下:
<bean id="logJob1"
class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<value>quartz1.LogJob</value>
</property>
<property name="jobDataAsMap">
<map>
<entry key="timeout">
<value>10</value>
</entry>
</map>
</property>
</bean>
<bean id="trigger1"
class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail">
<ref bean="logJob1"></ref>
</property>
<property name="startDelay">
<value>5000</value>
</property>
<property name="repeatInterval">
<value>2000</value>
</property>
<property name="repeatCount">
<value>0</value>
</property>
</bean>
<bean id="sfb"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref local="trigger1" />
</list>
</property>
</bean>定时服务如何启动呢,有人看过SchedulerFactoryBean可能会注意到一个start()方法,错误的利用此方法来启动定时服务。其实定时服务是不需要启动的,在spring配置文件装载时定时服务会自动启动。
本文介绍了在项目中使用Quartz作为定时服务的场景,以及Spring如何支持Quartz。内容涉及Quartz的两种实现方式,包括实现QuartzJobBean以及通过Spring包装成quartzjobbean。配置触发器后,定时服务会在Spring配置文件加载时自动启动。
401

被折叠的 条评论
为什么被折叠?



