前情提要
在進行開發的時候,通常我們需要設置一個定時的任務,比如定時清理應用緩存等,對於這種情況,我們可以在前端通過js創建定時任務發送http來實現,而這看起來卻類似輪詢了,並且隨着使用時長的增加,發送的http請求也相應的增加。SpringBoot可以非常簡單的實現這個功能
SpringBoot創建一個簡單的定時任務
首先創建定時任務類:
package org.framework.demo.section1;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* 設置一個定時任務
* @author chengxi
*/
@Configuration
@EnableScheduling
public class ScheduleConfig {
@Scheduled(cron = "0/20 * * * * ?")
public void scheduler(){
System.out.println("執行了喲");
}
}
然後編寫tomcat啓動類:啓動類測試代碼這裏就不貼了,前面的系列篇都有,都可以用於測試
然後啓動tomcat啓動類,查看控制檯,就會發現每過20S都會輸出執行了喲
,即表示定時任務創建成功