Spring Schedule Task動(dòng)態(tài)改寫(xiě)Cron配置
使用Spring @Scheduled標(biāo)簽可以很簡(jiǎn)單地定義Scheduled Task,但是有時(shí)我們需要在程序里動(dòng)態(tài)地改寫(xiě)Cron的配置。
什么時(shí)候呢?
額,比如:
老板覺(jué)得Cron配置太難看了,想直接這樣:10:15
Scheduling Tasks的常規(guī)使用
兩個(gè)標(biāo)簽: @EnableScheduling, @Scheduled
1
2
3
4
5
6
7
|
@SpringBootApplication @EnableScheduling public class SchedulingTasksApplication { public static void main(String[] args) { SpringApplication.run(SchedulingTasksApplication. class ); } } |
1
2
3
4
5
6
7
8
|
public class ScheduleTaskSimpleJob { @Scheduled (cron = "0 15 10 * * ?" ) public void scheduleCronTask() { long now = System.currentTimeMillis() / 1000 ; System.out.println( "schedule tasks using cron jobs - " + now); } } |
動(dòng)態(tài)改寫(xiě)Cron
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
Implements SchedulingConfigurer就可以,想怎么改怎么改。 public class ScheduleTaskSimpleJob implements SchedulingConfigurer { public void scheduleCronTask() { long now = System.currentTimeMillis() / 1000 ; System.out.println( "schedule tasks using cron jobs - " + now); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addTriggerTask( new Runnable() { @Override public void run() { scheduleCronTask(); } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { //TODO 將時(shí)間配置10:15轉(zhuǎn)換為cron String cron = "0 15 10 * * ?" ; CronTrigger trigger = new CronTrigger(cron); Date nextExecDate = trigger.nextExecutionTime(triggerContext); return nextExecDate; } }); } } |
@Scheduled定時(shí)任務(wù)動(dòng)態(tài)修改cron參數(shù)
Spring框架自3.0版本起,自帶了任務(wù)調(diào)度功能,好比是一個(gè)輕量級(jí)的Quartz,而且使用起來(lái)也方便、簡(jiǎn)單,且不需要依賴其他的JAR包。秉承著Spring的一貫風(fēng)格,Spring任務(wù)調(diào)度的實(shí)現(xiàn)同時(shí)支持注解配置和XML配置兩種方式。
再來(lái)談?wù)勛儜B(tài)的項(xiàng)目需求:我們正在做一個(gè)智能數(shù)字電表的數(shù)據(jù)采集項(xiàng)目,項(xiàng)目最終會(huì)在多個(gè)工業(yè)園上線,每個(gè)工業(yè)園對(duì)電表數(shù)據(jù)的采集周期可以進(jìn)行自定義,例如A工業(yè)園想每10分鐘采集一次數(shù)據(jù),B工業(yè)園想每15分鐘采集一次數(shù)據(jù)。因?yàn)閿?shù)據(jù)采集是個(gè)重復(fù)的周期性工作,那么就可以考慮使用Spring框架的定時(shí)任務(wù)功能了。
按正常來(lái)講,修改定時(shí)任務(wù)的執(zhí)行周期還不簡(jiǎn)單,把服務(wù)停下來(lái),改下任務(wù)的cron參數(shù),再重啟服務(wù)就搞定了。但有沒(méi)有一種可能,在不停服務(wù)的情況下,就可以動(dòng)態(tài)的修改任務(wù)的cron參數(shù)呢?完全是有可能的!
先來(lái)看下Spring常規(guī)定時(shí)任務(wù)的配置
如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<? 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:task = "http://www.springframework.org/schema/task" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> < context:component-scan base-package = "com.pes_soft.task.demo" /> <!-- Spring注解方式配置調(diào)度任務(wù) --> < task:executor id = "executor" pool-size = "3" /> < task:scheduler id = "scheduler" pool-size = "3" /> < task:annotation-driven executor = "executor" scheduler = "scheduler" /> </ beans > |
注意:配置Spring定時(shí)任務(wù)時(shí),需要在Spring配置文件的xml頭部加入
xmlns:task="http://www.springframework.org/schema/task"和xsi:schemaLocation位置中加入
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
然后是注解式任務(wù)邏輯代碼SpringStaticCronTask.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package com.pes_soft.task.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Lazy ( false ) @Component public class SpringStaticCronTask { private static final Logger logger = LoggerFactory.getLogger(SpringStaticCronTask. class ); @Scheduled (cron= "0/5 * * * * ?" ) public void staticCronTask() { logger.debug( "staticCronTask is running..." ); } } |
上述任務(wù)適用于具有固定任務(wù)周期的任務(wù),若要修改任務(wù)執(zhí)行周期,只能走“停服務(wù)→修改任務(wù)執(zhí)行周期→重啟服務(wù)”這條路。
下面來(lái)看看可以在不停服務(wù)的情況下動(dòng)態(tài)修改任務(wù)周期的實(shí)現(xiàn)
步驟如下:
在定時(shí)任務(wù)類上增加@EnableScheduling注解,并實(shí)現(xiàn)SchedulingConfigurer接口。(值得注意的是:@EnableScheduling對(duì)Spring的版本要求比較高,一開(kāi)始使用的3.2.6版本時(shí)一直未成功,后來(lái)改成4.2.5版本就可以了)
設(shè)置一個(gè)靜態(tài)變量cron,用于存放任務(wù)執(zhí)行周期參數(shù)。
另辟一線程,用于模擬實(shí)際業(yè)務(wù)中外部原因修改了任務(wù)執(zhí)行周期。
設(shè)置任務(wù)觸發(fā)器,觸發(fā)任務(wù)執(zhí)行,其中就可以修改任務(wù)的執(zhí)行周期。
完整的SpringDynamicCronTask.java代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
package com.pes_soft.task.demo; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Component; @Lazy ( false ) @Component @EnableScheduling public class SpringDynamicCronTask implements SchedulingConfigurer { private static final Logger logger = LoggerFactory.getLogger(SpringDynamicCronTask. class ); private static String cron; public SpringDynamicCronTask() { cron = "0/5 * * * * ?" ; // 開(kāi)啟新線程模擬外部更改了任務(wù)執(zhí)行周期 new Thread( new Runnable() { @Override public void run() { try { Thread.sleep( 15 * 1000 ); } catch (InterruptedException e) { e.printStackTrace(); } cron = "0/10 * * * * ?" ; System.err.println( "cron change to: " + cron); } }).start(); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addTriggerTask( new Runnable() { @Override public void run() { // 任務(wù)邏輯 logger.debug( "dynamicCronTask is running..." ); } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { // 任務(wù)觸發(fā),可修改任務(wù)的執(zhí)行周期 CronTrigger trigger = new CronTrigger(cron); Date nextExec = trigger.nextExecutionTime(triggerContext); return nextExec; } }); } } |
將demo運(yùn)行起來(lái),查看任務(wù)執(zhí)行情況,可以觀察到任務(wù)的執(zhí)行周期由5秒變成了10秒,期間服務(wù)并未停止。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/prufeng/article/details/116565999