項目中使用分布式並發部署定時任務,多台跨JVM,按照常理邏輯每個JVM的定時任務會各自運行,這樣就會存在問題,多台分布式JVM機器的應用服務同時干活,一個是加重服務負擔,另外一個是存在嚴重的邏輯問題,比如需要回滾的數據,就回滾了多次,剛好quartz提供很好的解決方案。
集群分布式並發環境中使用QUARTZ定時任務調度,會在各個節點會上報任務,存到數據庫中,執行時會從數據庫中取出觸發器來執行,如果觸發器的名稱和執行時間相同,則只有一個節點去執行此任務。
如果此節點執行失敗,則此任務則會被分派到另一節點執行,中途也會自動檢查失效的定時調度,發現不成功的,其他節點立馬接過來繼續完成定時任務。對應的定時任務調度表比較多,有11個。
此方法是結合Spring與quartz,實際解決方案如下:
####applicationContext-scheduler.xml### spring 3.11
<?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:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"> <context:annotation-config /> <context:component-scan base-package="com.dennis.walking.api.web.schedule" /> <bean id="rollbackOrderStatus" class="org.springframework.scheduling.quartz.JobDetailFactoryBean"> <property name="jobClass" value="com.dennis.walking.api.web.schedule.ReleaseQtyAndUpdateOrderStatusSchedule" /> <property name="durability" value="true" /> </bean> <bean id="rollbackOrderStatusTrigger" class="com.dennis.walking.api.web.schedule.PersistableCronTriggerFactoryBean"> <property name="jobDetail" ref="rollbackOrderStatus" /> <property name="cronExpression"> <value>0 0/5 * * * ?</value> </property> <property name="timeZone"> <value>GMT+8:00</value> </property> </bean> <bean id="quartzScheduler" parent="baseQuartzScheduler"> <property name="configLocation" value="classpath:quartz.properties" /> <property name="autoStartup" value="true" /> <!-- This name is persisted as SCHED_NAME in db. for local testing could change to unique name to avoid collision with dev server --> <property name="schedulerName" value="apiQuartzScheduler" /> <!-- NOTE: Must add both the jobDetail and trigger to the scheduler! --> <property name="triggers"> <list> <ref bean="rollbackOrderStatusTrigger" /> </list> </property> <property name="jobDetails"> <list> <ref bean="rollbackOrderStatus" /> </list> </property> </bean> <bean id="baseQuartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <!-- <property name="configLocation" value="classpath:quartz.properties" /> --> <property name="dataSource"