yjhexy 发表于 2013-2-7 17:01:45

Quartz 学习第二课

根据官方文档上写的一些内容,因为发现文档写的不太详细:http://www.redsaga.com/spring_ref/2.0/html/scheduling.html
,所以自己尝试了下。记录了下来:
 
1,想要执行的任务实现了Quartz的接口,例如:
public class RepeatPartBuild implements StatefulJob {    private int i;    public void execute(JobExecutionContext context) throws JobExecutionException {      System.out.println("build " + (i++) + "次");    }} 那么Spring里可以这样配置:
<bean name="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean"><property name="jobClass" value="com.yajun.template.service.RepeatPartBuild" /></bean><bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"><!-- see the example of method invoking job above --><property name="jobDetail" ref="jobDetail" /><!-- 10 seconds --><property name="startDelay" value="1000" /><!-- repeat every 50 seconds --><property name="repeatInterval" value="5000" /></bean><bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"><property name="triggers"><list><ref bean="simpleTrigger" /></list></property></bean> 主要注意到 用到了spring里面的这个类:
org.springframework.scheduling.quartz.JobDetailBean来辅助我们使用Spring 来整合 Quartz调度。
这里的注意点:
com.yajun.template.service.RepeatPartBuild 这个类每5秒执行的时候都会是一个新的类。所以线程安全。
 
2,想要执行的任务是一个普通的POJO
例如对上述类增加了个build方法:
public class RepeatPartBuild {    private int i;    public void build() {      System.out.println("build");    }} spring配置如下:
<bean id="repeatPartBuild" class="com.yajun.template.service.RepeatPartBuild"></bean><bean id="jobDetail"class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"><property name="targetObject" ref="repeatPartBuild" /><property name="targetMethod" value="build" /><property name="concurrent" value="false" /></bean><bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"><!-- see the example of method invoking job above --><property name="jobDetail" ref="jobDetail" /><!-- 10 seconds --><property name="startDelay" value="1000" /><!-- repeat every 50 seconds --><property name="repeatInterval" value="5000" /></bean><bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"><property name="triggers"><list><ref bean="simpleTrigger" /></list></property></bean> 关键点在:
org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean这个类有
targetMethod可以指定要使用哪个方法。


这里值得注意的是文档上,可能是我没有理解,感觉没有写清楚以下这个类在用的时候控制不能并发的话只要配置
org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean<property name="concurrent" value="false" />就可以了,至于
com.yajun.template.service.RepeatPartBuild就完全没有必要继承 StateFul接口了。这个点感觉文档写得比较模糊,我自己测试证明了下。
页: [1]
查看完整版本: Quartz 学习第二课