项目使用的是SpringMVC, 以前就已经集成了 1.x 版本的 Quartz,有专门的配置文件定义了需要的bean。
一、配置文件示例如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"
>
<!-- 定时装置所要执行的任务所在的类 -->
<bean id="xxxJob" class="XXX"/>
<!-- 引用任务描述 -->
<bean id="methodInvokingJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<!-- 引用任务方法所在的类 -->
<ref bean="xxxJob" />
</property>
<property name="targetMethod">
<!-- 指定任务方法名称 -->
<value>xxxMenthod</value>
</property>
</bean>
<!-- 配置触发器 -->
<bean id="xxxTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<!-- 这里不可以直接在属性jobDetail中引用taskJob,因为他要求的是一个jobDetail类型的对象,所以我们得通过MethodInvokingJobDetailFactoryBean来转一下 -->
<property name="jobDetail">
<!-- 引用任务描述bean -->
<ref bean="methodInvokingJobDetail" />
</property>
<!-- 每天的8点到21点每隔1分钟触发,具体说明见附录 -->
<property name="cronExpression">
<!-- 秒 分 时 日 月 周 年 -->
<value>0 0 07,12,15,23 * * ?</value>
</property>
</bean>
<!-- 配置任务工厂, 只能有一个这种bean -->
<bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!-- 添加触发器 -->
<property name="triggers">
<list>
<ref local="xxxTrigger" />
<!-- ... -->
</list>
</property>
</bean>
</beans>
注意:schedulerFactory 只能定义一个,不然在工程启动的时候会报错。
二、实现程序对定时任务执行的控制
目前拟实现一个控制定时任务执行的服务类,供控制层调用,包括对运行中的Quartz中触发器的增、删和修改。
在这个服务类中,可以通过依赖注入注解拿到配置好的 SchedulerFactoryBean 和 触发器bean,例如:
@Autowired
SchedulerFactoryBean schedulerFactory;
@Autowired
CronTriggerBean xxxTrigger;
拿到 SchedulerFactoryBean 的 bean 以后,就可以借此获得获得 Scheduler 对象 scheduler :
Scheduler scheduler = schedulerFactory.getScheduler();
通过 scheduler 可以取消和新增任务计划的触发器了:
try {
scheduler.unscheduleJob("xxxTrigger", Scheduler.DEFAULT_GROUP);
} catch (SchedulerException e) {
e.printStackTrace();
}
try {
String newExpression = "5/1 * * * * ?";
xxxTrigger.setCronExpression(newExpression);
scheduler.scheduleJob(xxxTrigger);
} catch (SchedulerException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有