SpringBoot內置定時任務

springBoot內置定時任務

應用場景

業務監控,定時發送郵件,定時刪除緩存等等。spring

Spring Boot 內置定時

pom 包配置緩存

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
</dependencies>

啓動類開啓定時spring-boot

在啓動類上面加上@EnableScheduling便可開啓定時:this

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

建立定時任務實現類.net

使用 Spring Boot 自帶的定時很是的簡單,只須要在方法上面添加 @Scheduled 註解便可。設置 process() 每隔六秒執行一次,並統計執行的次數。code

[[@Component](https://my.oschina.net/u/3907912)]
public class SchedulerTask {

    private int count = 0;

    @Scheduled(cron="*/6 * * * * ?")
    public void process() {
        System.out.println("this is scheduler task runing  "+(count++));
    }

}

@Component
public class SchedulerTask2 {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    /**
     * @Scheduled(fixedRate = 6000) :上一次開始執行時間點以後 6 秒再執行。
     */
    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {
        System.out.println("如今時間:" + dateFormat.format(new Date()));
    }
}

啓動項目以後,就會在控制檯看到打印的結果,結果以下:orm

this is scheduler task runing  0
如今時間:09:44:17
this is scheduler task runing  1
如今時間:09:44:23
this is scheduler task runing  2
如今時間:09:44:29
this is scheduler task runing  3
如今時間:09:44:35

說明兩個方法都按照固定 6 秒的頻率來執行。ci

參數說明it

@Scheduled 參數能夠接受兩種定時的設置,一種是經常使用的cron="*/6 * * * * ?",一種是 fixedRate = 6000,兩種均可表示固定週期執行定時任務。io

fixedRate 說明

  • @Scheduled(fixedRate = 6000) :上一次開始執行時間點以後 6 秒再執行。
  • @Scheduled(fixedDelay = 6000) :上一次執行完畢時間點以後 6 秒再執行。
  • @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲 1 秒後執行,以後按 fixedRate 的規則每 6 秒執行一次。

cron 說明

cron 一共有 7 位,最後一位是年,Spring Boot 定時方案中只須要設置 6 位便可:

- 第一位,表示秒,取值 0-59;
- 第二位,表示分,取值 0-59;
- 第三位,表示小時,取值 0-23;
- 第四位,日期天/日,取值 1-31;
- 第五位,日期月份,取值 1-12;
- 第六位,星期,取值 1-7,星期1、星期二…;
注:不是第1周、第2周的意思,另外:1表示星期天,2表示星期一。
- 第七位,年份,能夠留空,取值 1970-2099。

cron 中,還有一些特殊的符號,含義以下:

(*)星號:能夠理解爲每的意思,每秒、每分、天天、每個月、每一年……。
(?)問號:問號只能出如今日期和星期這兩個位置,表示這個位置的值不肯定,天天 3 點執行,因此第六位星期的位置是不須要關注的,就是不肯定的值。同時,日期和星期是兩個相互排斥的元素,經過問號來代表不指定值。假如 1 月 10 日是星期一,若是在星期的位置是另指定星期二,就先後衝突矛盾了。
(-)減號:表達一個範圍,如在小時字段中使用「10-12」,則表示從 10~12 點,即 十、十一、12。
(,)逗號:表達一個列表值,如在星期字段中使用「一、二、4」,則表示星期1、星期2、星期四。
(/)斜槓:如 x/y,x 是開始值,y 是步長,好比在第一位(秒) 0/15 就是,從 0 秒開始,每 15 秒,最後就是 0、1五、30、4五、60,另 */y,等同於 0/y。

下面列舉幾個經常使用的例子。

0 0 3 * * ?     天天 3 點執行。
0 5 3 * * ?     天天 3 點 5 分執行。
0 5 3 ? * *     天天 3 點 5 分執行,與上面做用相同。
0 5/10 3 * * ?  天天 3 點的 5 分、15 分、25 分、35 分、45 分、55 分這幾個時間點執行。
0 10 3 ? * 1    每週星期天,3點10分 執行,注:1 表示星期天。  
0 10 3 ? * 1#3  每月的第 三 個星期,星期天執行,# 號只能出如今星期的位置。

以上就是 Spring Boot 自定的定時方案,使用起來很是的簡單方便。

結束

若是僅須要執行簡單定時任務,就可使用 Spring Boot 自帶 Scheduled,能夠很是簡單和方便的使用。

相關文章
相關標籤/搜索