在咱們開發項目過程當中,常常須要定時任務來幫助咱們來作一些內容, Spring Boot 默認已經幫咱們實行了,只須要添加相應的註解就能夠實現java
pom 包裏面只須要引入 Spring Boot Starter 包便可git
<dependencies>
github
<dependency>
面試
<groupId>org.springframework.boot</groupId>
spring
<artifactId>spring-boot-starter</artifactId>
spring-boot
</dependency>
this
<dependency>
spa
<groupId>org.springframework.boot</groupId>
3d
<artifactId>spring-boot-starter-test</artifactId>
code
<scope>test</scope>
</dependency>
</dependencies>
在啓動類上面加上 @EnableScheduling
便可開啓定時
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
定時任務1:
@Component
public class SchedulerTask {
private int count=0;
@Scheduled(cron="*/6 * * * * ?")
private void process(){
System.out.println("this is scheduler task runing "+(count++));
}
}
定時任務2:
@Component
public class Scheduler2Task {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
System.out.println("如今時間:" + dateFormat.format(new Date()));
}
}
結果以下:
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
@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() 的關係
強烈推薦:
《Java 極客技術》知識星球限時優惠,如今加入只需 50 元,僅限前 1000 名,機不可失時再也不來。趁早行動吧!
https://t.zsxq.com/J6Em2nU
隆重介紹:
Java 極客技術公衆號,是由一羣熱愛 Java 開發的技術人組建成立,專一分享原創、高質量的 Java 文章。若是您以爲咱們的文章還不錯,請幫忙讚揚、在看、轉發支持,鼓勵咱們分享出更好的文章。