SpringBoot2定時任務

SpringBoot默認已經實現了定時任務。

啓動類啓用定時

在啓動類上面加上@EnableScheduling即可開啓定時。

package com.wu.parker.schedule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * @author: wusq
 * @date: 2019/1/10
 */
@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class, args);
    }
}

創建定時任務實現類
package com.wu.parker.schedule.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author: wusq
 * @date: 2019/1/10
 */
@Component
public class MyTask {

    @Scheduled(cron="*/6 * * * * ?")
    private void execute(){
        System.out.println("每6秒執行一次");
    }

}

@Scheduled 參數可以接受兩種定時的設置,一種是我們常用的cron="*/6 * * * * ?",一種是fixedRate=6000,兩種都表示每隔六秒打印一下內容。
cron用法比較通用,目前看到的講得好的資料是《Spring 3.x企業應用開發實戰》第13章-任務調度和異步執行器。

源代碼

https://github.com/wu-boy/parker.git
parker-schedule模塊

參考資料

springboot(九):定時任務

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章