⑤SpringBoot之定時任務
阿新 • • 發佈:2018-08-06
top cati current 啟動 ima 表示 spring clas EDA
本文介紹SpringBoot定時任務的使用,springboot默認已經幫我們實行了,只需要添加相應的註解就可以實現。
1.pom配置文件
pom包裏面只需要引入springboot starter包即可。
<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>
2、啟動類啟用定時
在啟動類上面加上@EnableScheduling即可開啟定時。
@SpringBootApplication @EnableScheduling public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
3、創建定時任務實現類
import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class SchedulerTask { private int count=0; private static final SimpleDateFormat dateFormat = newSimpleDateFormat("HH:mm:ss"); @Scheduled(cron="*/6 * * * * ?") private void process(){ System.out.println("this is scheduler task runing "+(count++)); } @Scheduled(fixedRate = 6000) public void reportCurrentTime() { System.out.println("現在時間:" + dateFormat.format(new Date())); } }
參數說明:
@Scheduled 參數可以接受兩種定時的設置,一種是我們常用的cron=”*/6 * * * * ?”,一種是 fixedRate = 6000,兩種都表示每隔六秒打印一下內容。
fixedRate 說明
@Scheduled(fixedRate = 6000) :上一次開始執行時間點之後6秒再執行;
@Scheduled(fixedDelay = 6000) :上一次執行完畢時間點之後6秒再執行;
@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延遲1秒後執行,之後按fixedRate的規則每6秒執行一次。
控制臺輸出:
如果使用static變量,假設 private static boolean isStop=false;
在定時器的方法中首行加一行代碼:if(isStop) return;
如果需要停止定時器,你寫個頁面,控制isStop的值就可以開關定時器了。
⑤SpringBoot之定時任務