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接口了。这个点感觉文档写得比较模糊,我自己测试证明了下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值