SpringBoot---(15)Spring Boot創建定時任務

摘要:項目中經常會需要做一些定時的跑的事情,比如每間隔多久做個統計,發個郵件,清理個數據。這時候就要用到定時任務,SpringBoot中,創建定時任務非常簡單,具體步驟如下:

1.開啓定時任務

在程序的入口類中添加@EnableScheduling註解

[java] view plain copy
  1. package com.alibaba;  
  2.   
  3. import org.mybatis.spring.annotation.MapperScan;  
  4. import org.springframework.boot.SpringApplication;  
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  6. import org.springframework.cache.annotation.EnableCaching;  
  7. import org.springframework.scheduling.annotation.EnableAsync;  
  8. import org.springframework.scheduling.annotation.EnableScheduling;  
  9. import org.springframework.web.bind.annotation.RequestMapping;  
  10. import org.springframework.web.bind.annotation.RequestMethod;  
  11. import org.springframework.web.bind.annotation.RestController;  
  12.   
  13. /** 
  14.  * the entrance of the application 
  15.  */  
  16. @EnableAsync  
  17. @RestController  
  18. @SpringBootApplication  
  19. @EnableCaching  
  20. @EnableScheduling  
  21. //掃描dao  
  22. @MapperScan("com.alibaba.dao")  
  23. public class TmallApplication {  
  24.   
  25.     public static void main(String[] args) {  
  26.         SpringApplication.run(TmallApplication.class, args);  
  27.     }  
  28.   
  29.     @RequestMapping(value = "hello",method = RequestMethod.GET)  
  30.     public String getHello(){  
  31.         return "hello world";  
  32.     }  

2.創建建定時任務

單獨創建一個類,用來存放定時任務,然後在每個定時任務方法上,用註解標明定時任務的執行週期。我這裏以每間隔10秒打印一下當前系統時間爲例。

[java] view plain copy
  1. package com.alibaba.task;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.scheduling.annotation.Scheduled;  
  6. import org.springframework.stereotype.Component;  
  7.   
  8. /** 
  9.  * Created by lightClouds917 
  10.  * Date 2018/2/6 
  11.  * Description:定時任務 
  12.  */  
  13. @Component  
  14. public class ScheduledTask {  
  15.     private final Logger logger = LoggerFactory.getLogger(getClass());  
  16.   
  17.     /** 
  18.      * 每間隔10秒輸出時間 
  19.      */  
  20.     @Scheduled(fixedRate = 10000)  
  21.     public void logTime(){  
  22.         logger.info("定時任務,現在時間:"+System.currentTimeMillis());  
  23.   
  24.     }  

3.@Scheduled的幾種用法

@Scheduled(fixedRate = 5000) :上一次開始執行時間點之後5秒再執行
@Scheduled(fixedDelay = 5000) :上一次執行完畢時間點之後5秒再執行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延遲1秒後執行,之後按fixedRate的規則每5秒執行一次
@Scheduled(cron="*/5 * * * * *") :通過cron表達式定義規則
注意,這裏的時間,單位是毫秒,1秒=1000毫秒

4.運行項目

發佈了123 篇原創文章 · 獲贊 164 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章