在项目中有进可能会用到定进服务,一些简单的定时服务可以用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配置文件装载时定时服务会自动启动。
最后
以上就是舒心乌冬面最近收集整理的关于spring 定时服务调度quartz(一)的全部内容,更多相关spring内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。

发表评论 取消回复