Spring Boot定時器創(chuàng)建及使用解析
創(chuàng)建定時器
因為項目需要定時在后端執(zhí)行任務(wù)刷新數(shù)據(jù),不需要從前端調(diào)用接口,所以需要使用定時器?;谧⒔夥绞紷Scheduled默認為單線程。
package com.ruanshuai.demo.util;import com.ruanshuai.demo.config.ConfigConsts;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;/** * @author ruanshuai * @date 2019/10/30 */@Component@EnableSchedulingpublic class TestSchedule { @Scheduled(fixedDelay = ConfigConsts.TEN_SECONDS) public void test(){ System.out.println('定時任務(wù)執(zhí)行開始!'); System.out.println('這是一個定時任務(wù)!'); System.out.println('定時任務(wù)執(zhí)行結(jié)束!'); }}
其中TEN_SECONDS表示10秒,定時器任務(wù)每10秒鐘自動執(zhí)行一個。
各種時間表示如下:
1 * 1000表示1秒; 60 * 1 * 1000表示1分鐘; 60 * 60 * 1 * 1000表示1小時; 24 * 60 * 60 * 1 * 1000表示1天;依此類推
package com.ruanshuai.demo.config;/** * @author ruanshuai * @date 2019/10/30 */public class ConfigConsts { public static final long TEN_SECONDS = 10 * 1 * 1000;}
啟動測試
啟動項目,定時器任務(wù)在項目啟動時執(zhí)行一次,之后每隔10秒自動執(zhí)行一次。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. js select支持手動輸入功能實現(xiàn)代碼2. asp.net core項目授權(quán)流程詳解3. CSS3中Transition屬性詳解以及示例分享4. jsp文件下載功能實現(xiàn)代碼5. 開發(fā)效率翻倍的Web API使用技巧6. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼7. vue使用moment如何將時間戳轉(zhuǎn)為標準日期時間格式8. html中的form不提交(排除)某些input 原創(chuàng)9. PHP橋接模式Bridge Pattern的優(yōu)點與實現(xiàn)過程10. ASP常用日期格式化函數(shù) FormatDate()
