在spring boot項(xiàng)目中,通過@enablescheduling可啟用spring自帶的定時任務(wù)支持,在通過@scheduled注解定義定時任務(wù),但是通過注解只能編寫固定時間的定時任務(wù),無法動態(tài)調(diào)整定時間隔,可通過實(shí)現(xiàn)schedulingconfigurer接口實(shí)現(xiàn)動態(tài)定時任務(wù)注冊。
對比quartz的優(yōu)缺點(diǎn)
優(yōu)點(diǎn):配置非常簡單
缺點(diǎn):
- 不支持分布式部署
- 不支持動態(tài)配置定時任務(wù)
- 不支持持久化
其實(shí)這幾個缺點(diǎn)歸根結(jié)底都是因?yàn)椴恢С殖志没匀绻?xiàng)目需要持久化定時任務(wù),還是要選擇quartz比較好。
參考代碼:
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
package org.cent.demo.scanner.schedule; import lombok.allargsconstructor; import lombok.data; import lombok.extern.slf4j.slf4j; import org.springframework.context.annotation.configuration; import org.springframework.scheduling.trigger; 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 java.util.arrays; import java.util.list; /** * @author: cent * @email: [email protected] * @date: 2019/1/16. * @description: */ @configuration @enablescheduling @slf4j public class dynamicschedule implements schedulingconfigurer { /** * 測試數(shù)據(jù),實(shí)際可從數(shù)據(jù)庫獲取 */ private list<task> tasks = arrays.aslist( new task( 1 , "任務(wù)1" , "*/30 * * * * *" ), new task( 2 , "任務(wù)2" , "*/30 * * * * *" ), new task( 3 , "任務(wù)3" , "*/30 * * * * *" ), new task( 4 , "任務(wù)4" , "*/30 * * * * *" ), new task( 5 , "任務(wù)5" , "*/30 * * * * *" ), new task( 6 , "任務(wù)6" , "*/30 * * * * *" ), new task( 7 , "任務(wù)7" , "*/30 * * * * *" ), new task( 8 , "任務(wù)8" , "*/30 * * * * *" ), new task( 9 , "任務(wù)9" , "*/30 * * * * *" ), new task( 10 , "任務(wù)10" , "*/30 * * * * *" ) ); @override public void configuretasks(scheduledtaskregistrar scheduledtaskregistrar) { tasks.foreach(task -> { //任務(wù)執(zhí)行線程 runnable runnable = () -> log.info( "execute task {}" , task.getid()); //任務(wù)觸發(fā)器 trigger trigger = triggercontext -> { //獲取定時觸發(fā)器,這里可以每次從數(shù)據(jù)庫獲取最新記錄,更新觸發(fā)器,實(shí)現(xiàn)定時間隔的動態(tài)調(diào)整 crontrigger crontrigger = new crontrigger(task.getcron()); return crontrigger.nextexecutiontime(triggercontext); }; //注冊任務(wù) scheduledtaskregistrar.addtriggertask(runnable, trigger); }); } @data @allargsconstructor static class task { /** * 主鍵id */ private int id; /** * 任務(wù)名稱 */ private string name; /** * cron表達(dá)式 */ private string cron; } } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.jianshu.com/p/546631cc2b8f