SpringBoot幾種定時任務的實現方式

定時任務實現的幾種方式:java

  • Timer:這是java自帶的java.util.Timer類,這個類容許你調度一個java.util.TimerTask任務。使用這種方式可讓你的程序按照某一個頻度執行,但不能在指定時間運行。通常用的較少。
  • ScheduledExecutorService:也jdk自帶的一個類;是基於線程池設計的定時任務類,每一個調度任務都會分配到線程池中的一個線程去執行,也就是說,任務是併發執行,互不影響。
  • Spring Task:Spring3.0之後自帶的task,能夠將它當作一個輕量級的Quartz,並且使用起來比Quartz簡單許多。
  • Quartz:這是一個功能比較強大的的調度器,可讓你的程序在指定時間執行,也能夠按照某一個頻度執行,配置起來稍顯複雜。

Timer與ScheduledExecutorService有篇已經介紹到了,這裏不在作介紹。

使用Spring Task

##簡單的定時任務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註解來設置任務的執行時間,而且使用三種屬性配置方式:

  1. fixedRate:定義一個按必定頻率執行的定時任務
  2. fixedDelay:定義一個按必定頻率執行的定時任務,與上面不一樣的是,改屬性能夠配合initialDelay, 定義該任務延遲執行時間。
  3. cron:經過表達式來配置任務執行時間

cron表達式詳解

一個cron表達式有至少6個(也可能7個)有空格分隔的時間元素。按順序依次爲:

  • 秒(0~59)
  • 分鐘(0~59)
  • 3 小時(0~23)
  • 4 天(0~31)
  • 5 月(0~11)
  • 6 星期(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
  • 年份(1970-2099)

其中每一個元素能夠是一個值(如6),一個連續區間(9-12),一個間隔時間(8-18/4)(/表示每隔4小時),一個列表(1,3,5),通配符。因爲」月份中的日期」和」星期中的日期」這兩個元素互斥的,必需要對其中一個設置。配置實例:

  • 每隔5秒執行一次:/5 * ?
  • 每隔1分鐘執行一次:0 /1 ?
  • 0 0 10,14,16 ? 天天上午10點,下午2點,4點
  • 0 0/30 9-17 ? 朝九晚五工做時間內每半小時
  • 0 0 12 ? * WED 表示每一個星期三中午12點
  • 「0 0 12 ?」 天天中午12點觸發
  • 「0 15 10 ? 「 天天上午10:15觸發
  • 「0 15 10 ?」 天天上午10:15觸發
  • 「0 15 10 ? *」 天天上午10:15觸發
  • 「0 15 10 ? 2005」 2005年的天天上午10:15觸發
  • 「0 14 * ?」 在天天下午2點到下午2:59期間的每1分鐘觸發
  • 「0 0/5 14 ?」 在天天下午2點到下午2:55期間的每5分鐘觸發
  • 「0 0/5 14,18 ?」 在天天下午2點到2:55期間和下午6點到6:55期間的每5分鐘觸發
  • 「0 0-5 14 ?」 在天天下午2點到下午2:05期間的每1分鐘觸發
  • 「0 10,44 14 ? 3 WED」 每一年三月的星期三的下午2:10和2:44觸發
  • 「0 15 10 ? * MON-FRI」 週一至週五的上午10:15觸發
  • 「0 15 10 15 * ?」 每個月15日上午10:15觸發
  • 「0 15 10 L * ?」 每個月最後一日的上午10:15觸發
  • 「0 15 10 ? * 6L」 每個月的最後一個星期五上午10:15觸發
  • 「0 15 10 ? * 6L 2002-2005」 2002年至2005年的每個月的最後一個星期五上午10:15觸發
  • 「0 15 10 ? * 6#3」 每個月的第三個星期五上午10:15觸發

有些子表達式能包含一些範圍或列表

例如:子表達式(天(星期))能夠爲 「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 , - * /


整合Quartz

  • 添加依賴

若是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/

相關文章
相關標籤/搜索