定時任務實現的幾種方式:java
##簡單的定時任務web
在SpringBoot項目中,咱們能夠很優雅的使用註解來實現定時任務,首先建立項目,導入依賴:spring
1 <dependencies>
2 <dependency>
3 <groupId>org.springframework.boot</groupId>
4 <artifactId>spring-boot-starter-web</artifactId>
5 </dependency>
6 <dependency>
7 <groupId>org.springframework.boot</groupId>
8 <artifactId>spring-boot-starter</artifactId>
9 </dependency>
10 <dependency>
11 <groupId>org.projectlombok</groupId>
12 <artifactId>lombok</artifactId>
13 <optional>true</optional>
14 </dependency>
15 <dependency>
16 <groupId>org.springframework.boot</groupId>
17 <artifactId>spring-boot-starter-test</artifactId>
18 <scope>test</scope>
19 </dependency>
20 </dependencies>
建立任務類:多線程
1 @Slf4j 2 @Component 3 public class ScheduledService { 4 @Scheduled(cron = "0/5 * * * * *") 5 public void scheduled(){ 6 log.info("=====>>>>>使用cron {}",System.currentTimeMillis()); 7 } 8 @Scheduled(fixedRate = 5000) 9 public void scheduled1() { 10 log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis()); 11 } 12 @Scheduled(fixedDelay = 5000) 13 public void scheduled2() { 14 log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis()); 15 } 16 }
在主類上使用@EnableScheduling註解開啓對定時任務的支持,而後啓動項目建立任務類:併發
1 import org.springframework.boot.SpringApplication; 2 import org.springframework.boot.autoconfigure.SpringBootApplication; 3 import org.springframework.scheduling.annotation.EnableScheduling; 4
5 @SpringBootApplication 6 @EnableScheduling 7 public class SpringBootScheduledApplication { 8
9 public static void main(String[] args) { 10 SpringApplication.run(SpringBootScheduledApplication.class, args); 11 } 12 }
運行結果:異步
能夠看到三個定時任務都已經執行,而且使同一個線程中串行執行,若是隻有一個定時任務,這樣作確定沒問題,當定時任務增多,若是一個任務卡死,會致使其餘任務也沒法執行。ide
在傳統的Spring項目中,咱們能夠在xml配置文件添加task的配置,而在SpringBoot項目中通常使用config配置類的方式添加配置,因此新建一個AsyncConfig類spring-boot
1 @Configuration 2 @EnableAsync 3 public class AsyncConfig { 4 /* 5 此處成員變量應該使用@Value從配置中讀取 6 */ 7 private int corePoolSize = 10; 8 private int maxPoolSize = 200; 9 private int queueCapacity = 10; 10 @Bean 11 public Executor taskExecutor() { 12 ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 13 executor.setCorePoolSize(corePoolSize); 14 executor.setMaxPoolSize(maxPoolSize); 15 executor.setQueueCapacity(queueCapacity); 16 executor.initialize(); 17 return executor; 18 } 19 }
@Configuration
:代表該類是一個配置類 ui
@EnableAsync
:開啓異步事件的支持spa
而後在定時任務的類或者方法上添加@Async
。最後重啓項目,每個任務都是在不一樣的線程中
在上面的定時任務中,咱們在方法上使用@Scheduled註解來設置任務的執行時間,而且使用三種屬性配置方式:
initialDelay
, 定義該任務延遲執行時間。一個cron表達式有至少6個(也可能7個)有空格分隔的時間元素。按順序依次爲:
其中每一個元素能夠是一個值(如6),一個連續區間(9-12),一個間隔時間(8-18/4)(/表示每隔4小時),一個列表(1,3,5),通配符。因爲」月份中的日期」和」星期中的日期」這兩個元素互斥的,必需要對其中一個設置。配置實例:
有些子表達式能包含一些範圍或列表
例如:子表達式(天(星期))能夠爲 「MON-FRI」,「MON,WED,FRI」,「MON-WED,SAT」
「*」字符表明全部可能的值
「/」字符用來指定數值的增量
例如:在子表達式(分鐘)裏的「0/15」表示從第0分鐘開始,每15分鐘
在子表達式(分鐘)裏的「3/20」表示從第3分鐘開始,每20分鐘(它和「3,23,43」)的含義同樣
「?」字符僅被用於天(月)和天(星期)兩個子表達式,表示不指定值
當2個子表達式其中之一被指定了值之後,爲了不衝突,須要將另外一個子表達式的值設爲「?」
「L」 字符僅被用於天(月)和天(星期)兩個子表達式,它是單詞「last」的縮寫
若是在「L」前有具體的內容,它就具備其餘的含義了。
例如:「6L」表示這個月的倒數第6天
注意:在使用「L」參數時,不要指定列表或範圍,由於這會致使問題
W 字符表明着平日(Mon-Fri),而且僅能用於日域中。它用來指定離指定日的最近的一個平日。大部分的商業處理都是基於工做周的,因此 W 字符多是很是重要的。
例如,日域中的 15W 意味着 「離該月15號的最近一個平日。」 假如15號是星期六,那麼 trigger 會在14號(星期五)觸發,由於星期四比星期一離15號更近。
C:表明「Calendar」的意思。它的意思是計劃所關聯的日期,若是日期沒有被關聯,則至關於日曆中全部日期。
例如5C在日期字段中就至關於日曆5日之後的第一天。1C在星期字段中至關於星期往後的第一天。
字段 | 容許值 | 容許的特殊字符 |
---|---|---|
秒 | 0~59 | , - * / |
分 | 0~59 | , - * / |
小時 | 0~23 | , - * / |
日期 | 1-31 | , - * ? / L W C |
月份 | 1~12或者JAN~DEC | , - * / |
星期 | 1~7或者SUN~SAT | , - * ? / L C # |
年(可選) | 留空,1970~2099 | , - * / |
若是SpringBoot版本是2.0.0之後的,則在spring-boot-starter中已經包含了quart的依賴,則能夠直接使用spring-boot-starter-quartz
依賴:
1 <dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-quartz</artifactId>
4 </dependency>
若是是1.5.9則要使用如下添加依賴:
1 <dependency>
2 <groupId>org.quartz-scheduler</groupId>
3 <artifactId>quartz</artifactId>
4 <version>2.3.0</version>
5 </dependency>
6 <dependency>
7 <groupId>org.springframework</groupId>
8 <artifactId>spring-context-support</artifactId>
9 </dependency>
這裏我使用SpringBoot版本是2.0.0.BUILD-SNAPSHOT
,該版本開始集成了Quartz,因此事實現起來很方便。其它好像比較麻煩,這裏就不介紹,之後有時間再詳細深刻了解Quartz。
建立任務類TestQuartz,該類主要是繼承了QuartzJobBean
1 public class TestQuartz extends QuartzJobBean { 2 /**
3 * 執行定時任務 4 * @param jobExecutionContext 5 * @throws JobExecutionException 6 */
7 @Override 8 protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { 9 System.out.println("quartz task "+new Date()); 10 } 11 }
建立配置類QuartzConfig
1 @Configuration 2 public class QuartzConfig { 3 @Bean 4 public JobDetail teatQuartzDetail(){ 5 return JobBuilder.newJob(TestQuartz.class).withIdentity("testQuartz").storeDurably().build(); 6 } 7
8 @Bean 9 public Trigger testQuartzTrigger(){ 10 SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() 11 .withIntervalInSeconds(10) //設置時間週期單位秒
12 .repeatForever(); 13 return TriggerBuilder.newTrigger().forJob(teatQuartzDetail()) 14 .withIdentity("testQuartz") 15 .withSchedule(scheduleBuilder) 16 .build(); 17 } 18 }
http://www.wanqhblog.top/2018/02/01/SpringBootTaskSchedule/