springBoot配置定時任務 @Scheduled


 

 

 

新知識點,@Scheduled,

作用:可以通過@Scheduled配置定時任務。

 

 1 package com.example.demo.scheduled;
 2 
 3 import java.time.LocalDateTime;
 4 import java.time.format.DateTimeFormatter;
 5 
 6 import org.springframework.scheduling.annotation.EnableScheduling;
 7 import org.springframework.scheduling.annotation.Scheduled;
 8 import org.springframework.stereotype.Component;
 9 
10 @Component
11 @EnableScheduling
12 public class scheduleTask {
13 
14     private DateTimeFormatter ofPattern;
15 
16     @Scheduled(cron = "0/5 * * * * ?")
17     public void task() {
18         LocalDateTime now = LocalDateTime.now();
19         ofPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
20         System.out.println(now.format(ofPattern)+"it is task");
21     }
22 }

展示的結果:

 

備注:

@Component,把類注入spring的上下文。

@EnableScheduling,開啟定時任務

@Scheduled,配置需要定時執行的任務,除了支持靈活的參數表達式cron之外,還支持簡單的延時操作,例如 fixedDelay ,fixedRate 填寫相應的毫秒數即可。

其中cron參數詳細信息如下:

Cron表達式參數分別表示:

  • 秒(0~59) 例如0/5表示每5秒
  • 分(0~59)
  • 時(0~23)
  • 日(0~31)的某天,需計算
  • 月(0~11)
  • 周幾( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)

備注:有一些網站,寫着定時任務,可以寫七個參數,最后一個參數,與年份相關。

查看 https://blog.csdn.net/fly910905/article/details/79566020 后,明白了 spring 3.0 后只支持 “6個參數”的cron


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM