Spring Boot(九):定時任務

​在咱們開發項目過程當中,常常須要定時任務來幫助咱們來作一些內容, Spring Boot 默認已經幫咱們實行了,只須要添加相應的註解就能夠實現java

一、pom 包配置

pom 包裏面只須要引入 Spring Boot Starter 包便可git

  1. <dependencies>github

  2. <dependency>面試

  3. <groupId>org.springframework.boot</groupId>spring

  4. <artifactId>spring-boot-starter</artifactId>spring-boot

  5. </dependency>this

  6. <dependency>spa

  7. <groupId>org.springframework.boot</groupId>3d

  8. <artifactId>spring-boot-starter-test</artifactId>code

  9. <scope>test</scope>

  10. </dependency>

  11. </dependencies>

二、啓動類啓用定時

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

  1. @SpringBootApplication

  2. @EnableScheduling

  3. public class Application {

  4.  

  5. public static void main(String[] args) {

  6. SpringApplication.run(Application.class, args);

  7. }

  8. }

三、建立定時任務實現類

定時任務1:

  1. @Component

  2. public class SchedulerTask {

  3.  

  4. private int count=0;

  5.  

  6. @Scheduled(cron="*/6 * * * * ?")

  7. private void process(){

  8. System.out.println("this is scheduler task runing "+(count++));

  9. }

  10.  

  11. }

定時任務2:

  1. @Component

  2. public class Scheduler2Task {

  3.  

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

  5.  

  6. @Scheduled(fixedRate = 6000)

  7. public void reportCurrentTime() {

  8. System.out.println("如今時間:" + dateFormat.format(new Date()));

  9. }

  10.  

  11. }

結果以下:

  1. this is scheduler task runing 0

  2. 如今時間:09:44:17

  3. this is scheduler task runing 1

  4. 如今時間:09:44:23

  5. this is scheduler task runing 2

  6. 如今時間:09:44:29

  7. this is scheduler task runing 3

  8. 如今時間:09:44:35

參數說明

@Scheduled 參數能夠接受兩種定時的設置,一種是咱們經常使用的 cron="*/6 * * * * ?",一種是 fixedRate=6000,兩種都表示每隔六秒打印一下內容。

fixedRate 說明

  • @Scheduled(fixedRate=6000) :上一次開始執行時間點以後6秒再執行

  • @Scheduled(fixedDelay=6000) :上一次執行完畢時間點以後6秒再執行

  • @Scheduled(initialDelay=1000,fixedRate=6000) :第一次延遲1秒後執行,以後按 fixedRate 的規則每6秒執行一次

 

示例代碼-https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-scheduler

精彩回顧:

面試點:Java 中 hashCode() 和 equals() 的關係

容器鏈接[Docker 系列-7]

現現在的技術浪潮中,咱們到底該作些什麼?

 

強烈推薦:

《Java 極客技術》知識星球限時優惠,如今加入只需 50 元,僅限前 1000 名,機不可失時再也不來。趁早行動吧!

https://t.zsxq.com/J6Em2nU

 

隆重介紹:

Java 極客技術公衆號,是由一羣熱愛 Java 開發的技術人組建成立,專一分享原創、高質量的 Java 文章。若是您以爲咱們的文章還不錯,請幫忙讚揚、在看、轉發支持,鼓勵咱們分享出更好的文章。

 

相關文章
相關標籤/搜索