Spring与Quartz整合实现定时任务配置指南
本文详细介绍如何在Spring框架中集成Quartz来实现定时任务调度,并重点说明任务并行与串行执行的配置方式。
Spring Quartz配置示例
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 调度器工厂Bean配置 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="dataSyncTrigger" />
</list>
</property>
<property name="quartzProperties">
<props>
<prop key="org.quartz.threadPool.threadCount">5</prop>
</props>
</property>
</bean>
<!-- 触发器配置 -->
<bean id="dataSyncTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail">
<ref bean="dataSyncJob" />
</property>
<property name="cronExpression">
<value>0 0 2 * * ?</value>
</property>
</bean>
<!-- 任务详情配置 -->
<bean id="dataSyncJob"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="scheduledTaskService" />
</property>
<property name="targetMethod">
<value>performSync</value>
</property>
</bean>
</beans>
任务并行与串行执行机制
在Quartz调度器中,任务的执行策略分为并行和串行两种模式:
- 并行执行:当触发时间到达时,立即启动新任务实例,即使当前任务仍在运行中
- 串行执行:触发时间到达时,需要等待正在执行的任务完成后,才开始执行下一个任务
通过MethodInvokingJobDetailFactoryBean创建的Job,可以使用concurrent属性控制是否允许并行执行。该属性对于处理耗时较长的业务逻辑特别重要:当业务处理时间超过任务的触发间隔时,此配置将决定任务的行为模式。
配置示例如下:
<bean id="batchProcessJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="taskExecutorService" />
<property name="targetMethod" value="executeBatch" />
<property name="concurrent" value="false" />
</bean>
当concurrent设置为false时,如果当前任务仍在执行,新触发的任务将延迟运行;当设置为true时,多个任务实例可以同时运行,实现并行处理。默认情况下,该值为true,即允许任务并行执行。