在咱們的項目開發過程當中,常常須要定時任務來幫助咱們來作一些內容,springboot默認已經幫咱們實行了,只須要添加相應的註解就能夠實現java
pom包裏面只須要引入springboot starter包便可git
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>複製代碼
在啓動類上面加上@EnableScheduling
便可開啓定時github
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}複製代碼
定時任務1:spring
@Component
public class SchedulerTask {
private int count=0;
@Scheduled(cron="*/6 * * * * ?")
private void process(){
System.out.println("this is scheduler task runing "+(count++));
}
}複製代碼
定時任務2:springboot
@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()));
}
}複製代碼
結果以下:spring-boot
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
,兩種都表示每隔六秒打印一下內容。this
fixedRate 說明spa
@Scheduled(fixedRate = 6000)
:上一次開始執行時間點以後6秒再執行@Scheduled(fixedDelay = 6000)
:上一次執行完畢時間點以後6秒再執行@Scheduled(initialDelay=1000, fixedRate=6000)
:第一次延遲1秒後執行,以後按fixedRate的規則每6秒執行一次示例代碼code
喜歡個人文章,請關注個人公衆號orm