爲什麼使用定時?
日常工作中,經常會用到定時任務,比如各種統計,並不要求實時性。此時可以通過提前設置定時任務先把數據跑出來,後續處理起來更方便. 本篇文章主要介紹 springboot內置定時任務。
實戰演示
1、pom文件
pom 包裏面只需要引入 Spring Boot Starter 包即可,Spring Boot Starter 包中已經內置了定時的方法。我這裏方便演示,增加了lombok
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
2、啓動類開啓定時
@SpringBootApplication
@EnableScheduling
public class ScheduledApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduledApplication.class, args);
}
}
3、創建定時任務實現類
這裏並沒有直接在類中寫cron語句,而是寫到了配置文件中。一般實際項目中這樣寫。
3.1、ScheduledTask 類
/**
* @author: curry
* @Date: 2018/10/10
*/
@Component
@Slf4j
public class ScheduledTask {
@Scheduled(cron = "${job.schedule}")
private void process1() {
log.info("start");
}
}
3.2 application.properties
job.schedule = */5 * * * * ?
4、執行結果
2018-10-10 22:48:55.001 [pool-1-thread-1] demo.ScheduledTask : start
2018-10-10 22:49:00.001 [pool-1-thread-1] demo.ScheduledTask : start
2018-10-10 22:49:05.001 [pool-1-thread-1] demo.ScheduledTask : start
2018-10-10 22:49:10.001 [pool-1-thread-1] demo.ScheduledTask : start
2018-10-10 22:49:15.001 [pool-1-thread-1] demo.ScheduledTask : start
corn 語法說明
cron 每位的含義
cron 一共有 7 位,最後一位是年,Spring Boot 定時方案中只需要設置 6 位即可:
- 第一位,表示秒,取值 0-59;
- 第二位,表示分,取值 0-59;
- 第三位,表示小時,取值 0-23;
- 第四位,日期天/日,取值 1-31;
- 第五位,日期月份,取值 1-12;
- 第六位,星期,取值 1-7,星期一、星期二…;
注:不是第1周、第2周的意思,另外:1表示星期天,2表示星期一。
- 第七位,年份,可以留空,取值 1970-2099。
cron 符號含義
(*)星號:可以理解爲每的意思,每秒、每分、每天、每月、每年……。
(?)問號:問號只能出現在日期和星期這兩個位置,表示這個位置的值不確定,每天 12 點執行,所以第六位星期的位置是不需要關注的,就是不確定的值。同時,日期和星期是兩個相互排斥的元素,通過問號來表明不指定值。
(-)減號:表達一個範圍,如在小時字段中使用“10-12”,則表示從 10~12 點,即 10、11、12。
(,)逗號:表達一個列表值,如在星期字段中使用“1、2、4”,則表示星期一、星期二、星期四。
(/)斜槓:如 x/y,x 是開始值,y 是步長,比如在第一位(秒) 0/15 就是,從 0 秒開始,每 15 秒,最後就是 0、15、30、45、60,另 */y,等同於 0/y。
舉個栗子
0 0 1 * * ? 每天 1 點執行。
0 5 1 * * ? 每天 1 點 5 分執行。
0-5 * * * * ? 每分鐘的0/1/2/3/4/5 秒執行
0 5/10 1 * * ? 每天 1 點的 5 分、15 分、25 分、35 分、45 分、55 分這幾個時間點執行。
0 5 1 ? * 1 每週星期天,1點5分 執行,注:1 表示星期天。
0 10 3 ? * 1#3 每個月的第 三 個星期,星期天執行,# 號只能出現在星期的位置。
fixedRate 說明
這個日常工作中很少用到,這裏不做詳細介紹
@Scheduled(fixedRate = 6000) :上一次開始執行時間點之後 6 秒再執行。
@Scheduled(fixedDelay = 6000) :上一次執行完畢時間點之後 6 秒再執行。
@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲 1 秒後執行,之後按 fixedRate 的規則每 6 秒執行一次。
總結
其實,使用內置的定時任務還是很方便的,但是,如果複雜的情況一般使用Quartz 。大家工作中一般都會見過這個東西。下篇文章一塊學習一下這個東西。