本文主要介紹如何在Spring Boot中使用定時任務,假設你已經建好了一個基礎的Spring Boot項目。首先,咱們在項目中創建一個定時任務。html
package hello; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) public void reportCurrentTime() { System.out.println("The time is now " + dateFormat.format(new Date())); } }
@Scheduled 註解用於標註這個方法是一個定時任務的方法,方法的執行週期是fixedRate,本例中是每隔5秒鐘運行一次,咱們也可使用更靈活的設置方法@Scheduled(cron="...") ,用一個表達式來設置定時任務。java
接下來,咱們在Application中設置啓用定時任務功能。spring
package hello; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class); } }
其中 @EnableScheduling 註解的做用是發現註解@Scheduled的任務並後臺執行。api
運行Spring Boot,輸出結果爲以下,每5秒鐘打印出當前時間。spa
The time is now 13:10:00 The time is now 13:10:05 The time is now 13:10:10 The time is now 13:10:15
參考資料.net
Spring定時任務的幾種實現code
http://blog.csdn.net/kaixuanfeng2012/article/details/14161285 orm