一、使用場景
定時任務在開發中還是比較常見的,比如:定時發送郵件,定時發送信息,定時更新資源,定時更新數據等等...
二、准備工作
在Spring Boot程序中不需要引入其他Maven依賴
(因為spring-boot-starter-web傳遞依賴了spring-context模塊)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
三、開始搭建配置
- 配置啟動項
package com.wang.test.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling//啟動定時任務
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- cron表達式
關於cron表達式,小編這里不做過多介紹,這里是cron生成器,大家可以參考
https://www.matools.com/cron/
- 定時任務方法
package com.wang.test.demo.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component//加載到容器中,可以被發現啟動
public class TaskTest {
//cron表達式,來控制定時執行時間,這里是每5秒執行一次本方法,業務邏輯可以進行在此方法內進行書寫
@Scheduled(cron = "0/5 * * * * ?")
public void printTimeOne(){
System.out.println("任務一:時間為-->"+System.currentTimeMillis());
}
@Scheduled(cron = "0/6 * * * * ?")
public void printTimeTwo(){
System.out.println("任務二:時間為-->"+System.currentTimeMillis());
}
}
四、結果展示
五、總結
這樣就完整了SpringBoot整合定時任務了,一個注解全搞定,非常簡潔好懂.