springboot定時任務就非常簡單!
1、添加依賴:引入 Spring Boot Starter 包即可
<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>
2、在啓動類上加上註解@EnableScheduling啓用定時
//開啓調度任務 @EnableScheduling
3、創建定時任務的實現類
這裏我做了兩個demo
a、
package cn.tycoding.timer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @Author: lilong
* @Data: Created on 2019/6/4
* @Desc: 定時任務1
*/
@Component
public class SchedulerTask {
private int count = 0;
@Scheduled(cron = "*/6 * * * * ?")
private void process(){
System.out.println(""+(count++));
}
}
b、
package cn.tycoding.timer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author: lilong
* @Data: Created on 2019/6/4
* @Desc: 定時任務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()));
}
}
運行結果如下:
再後面補充一些springboot定時器相關的用法代碼
package com.lilong.tasks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author: lilong
* @Data: Created on 2019/9/5
* @Desc: 創建定時任務
*/
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//通過在方法上加@Scheduled註解,表明該方法是一個調度任務。
@Scheduled(fixedRate = 5000)//上一次開始執行時間點之後5秒再執行
public void reportCurrentTime(){
log.info("上一次開始執行時間點之後5秒再執行的時間:{}",dateFormat.format(new Date()));
}
@Scheduled(fixedDelay = 5000)
public void reportCurrentTime2(){
log.info("上一次執行完畢時間點之後5秒再執行的時間 -- The time to reexecute 5 seconds after the last execution point:{}",dateFormat.format(new Date()));
}
@Scheduled(initialDelay = 1000,fixedDelay = 5000)
public void reportCurrentTime3(){
log.info("第一次延遲1秒後執行,之後按fixedRate的規則每5秒執行一次時間:{}",dateFormat.format(new Date()));
}
@Scheduled(cron = "*/6 * * * * ?")//cron表達式
public void reportCurrentTime4(){
log.info("自行搜索引擎的時間 -- Cron expression:{}",dateFormat.format(new Date()));
}
}
運行結果: