Scheduled如何會在上次任務執(zhí)行完才會執(zhí)行下次任務
更新時間:2024年08月02日 10:49:07 作者:hashdog
這篇文章主要介紹了Scheduled如何會在上次任務執(zhí)行完才會執(zhí)行下次任務問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Scheduled會在上次任務執(zhí)行完才會執(zhí)行下次任務
在使用spring的Scheduled定時任務
擔心同一任務,
第一次開始未執(zhí)行完就執(zhí)行第二次任務,所以給加了synchronized,
但是后面經過測試Scheduled定時任務會在上次任務結束時再執(zhí)行第二次任務,
如果第二次任務堵在哪里了,時間會順延
package xyz.hashdog.job; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * @author th * @description: 定時任務測試 * @projectName hashdog-ds * @date 2020/2/1223:07 */ @Component @Slf4j @AllArgsConstructor public class TestCrontab { private static final Object KEY = new Object(); private static boolean taskFlag = false; @Scheduled(cron = "*/5 * * * * ?") public void pushCancel() { System.out.println("進來了"); synchronized (KEY) { if (TestCrontab.taskFlag) { System.out.println("測試調度已經啟動"); log.warn("測試調度已經啟動"); return; } TestCrontab.taskFlag = true; } try { for (int i =0;i<=10;i++){ System.out.println("執(zhí)行:"+i); Thread.sleep(2000); } } catch (Exception e) { log.error("測試調度執(zhí)行出錯", e); } TestCrontab.taskFlag = false; log.warn("測試調度執(zhí)行完成"); } }
注釋掉synchronized
執(zhí)行效果一樣,并沒有線程安全問題
package xyz.hashdog.job; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * @author th * @description: 定時任務測試 * @projectName hashdog-ds * @date 2020/2/1223:07 */ @Component @Slf4j @AllArgsConstructor public class TestCrontab { private static final Object KEY = new Object(); private static boolean taskFlag = false; @Scheduled(cron = "*/5 * * * * ?") public void pushCancel() throws InterruptedException { System.out.println("進來了"); // synchronized (KEY) { // if (TestCrontab.taskFlag) { // System.out.println("測試調度已經啟動"); // log.warn("測試調度已經啟動"); // return; // } // TestCrontab.taskFlag = true; // } // // try { for (int i =0;i<=10;i++){ System.out.println("執(zhí)行:"+i); Thread.sleep(2000); } // } catch (Exception e) { // log.error("測試調度執(zhí)行出錯", e); // } // // TestCrontab.taskFlag = false; log.warn("測試調度執(zhí)行完成"); } }
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
MyBatis-Plus數(shù)據庫配置與數(shù)據源整合方案
本文詳細介紹了在MyBatis-Plus中進行數(shù)據庫配置與數(shù)據源整合的常見方法,包括單數(shù)據源和多數(shù)據源的配置步驟,以及如何使用SpringBoot的自動配置和手動配置來管理數(shù)據源,通過合理的配置,開發(fā)者可以簡化數(shù)據庫操作,實現(xiàn)高效的數(shù)據庫管理和復雜的應用架構2025-02-02java操作(DOM、SAX、JDOM、DOM4J)xml方式的四種比較與詳解
java中四種操作(DOM、SAX、JDOM、DOM4J)xml方式的比較與詳解2008-10-10spring boot 開發(fā)soap webservice的實現(xiàn)代碼
這篇文章主要介紹了spring boot 開發(fā)soap webservice的實現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01