您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“如何解決springboot定時(shí)任務(wù)@Scheduled執(zhí)行多次的問題”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
springboot定時(shí)任務(wù)@Scheduled執(zhí)行多次
原因
解決方法
使用 @Scheduled 定時(shí)任務(wù)突然不執(zhí)行了
在spring boot開發(fā)定時(shí)任務(wù)時(shí)遇到一個(gè)很怪異的現(xiàn)象..我進(jìn)行調(diào)試模式,在沒有bug的情況下.執(zhí)行了三 次才停止..如圖:
是因?yàn)閳?zhí)行時(shí)間太短,在CronSequenceGenerator.class的next方法。
public Date next(Date date) { Calendar calendar = new GregorianCalendar(); calendar.setTimeZone(this.timeZone); calendar.setTime(date); //1.設(shè)置下次執(zhí)行時(shí)間的毫秒為0,如上次任務(wù)執(zhí)行過程不足1秒,則calendar的時(shí)間會被設(shè)置成上次任務(wù)的執(zhí)行時(shí)間 calendar.set(14, 0); long originalTimestamp = calendar.getTimeInMillis(); this.doNext(calendar, calendar.get(1)); //2.由于有上面一步,執(zhí)行時(shí)間太短,會導(dǎo)致下述條件為true if(calendar.getTimeInMillis() == originalTimestamp) { //3.calendar在原來的時(shí)間上增加1秒 calendar.add(13, 1); //CronSequenceGenerator的doNext算法從指定時(shí)間開始(包括指定時(shí)間)查找符合cron表達(dá)式規(guī)則下一個(gè)匹配的時(shí)間 //注意第一個(gè)匹配符是*,由于增加了1秒,依然符合cron="* 0/2 * * * *",所以下一個(gè)執(zhí)行時(shí)間就是在原來的基礎(chǔ)上增加了一 秒 this.doNext(calendar, calendar.get(1)); } return calendar.getTime();
代碼會進(jìn)入if語句,并設(shè)置執(zhí)行時(shí)間在原來的基礎(chǔ)上增加一秒。
但由于增加一秒后的時(shí)間戳依然符合cron表達(dá)式,于是在執(zhí)行完代碼后一秒,任務(wù)又開始執(zhí)行了
程序執(zhí)行時(shí)間太短沒有關(guān)系,只要cron表達(dá)式秒的匹配符不設(shè)置為*就可以了。如圖:
在 SpringBoot 中可以通過 @Scheduled 注解來定義一個(gè)定時(shí)任務(wù), 但是有時(shí)候你可能會發(fā)現(xiàn)有的定時(shí)任務(wù)到時(shí)間了卻沒有執(zhí)行,但是又不是每次都不執(zhí)行,這是怎么回事?
下面這段代碼定義了一個(gè)每隔十秒鐘執(zhí)行一次的定時(shí)任務(wù):
@Component public class ScheduledTaskDemo { private static final Logger logger = LoggerFactory.getLogger(ScheduledTaskDemo.class); @Scheduled(cron = "0/10 * * * * *") public void execute() { logger.info("Scheduled task is running... ..."); } }
此時(shí)啟動(dòng) SpringBoot 應(yīng)用, 可以在控制臺看到這個(gè)定時(shí)任務(wù)每隔10秒鐘打印一條log
但是, 一切還沒結(jié)束,如果沒有相關(guān)log顯示, 檢查是否在入口類或者 Configuration 類上添加了@EnableScheduling 注解
在上面的相關(guān)代碼中, 我們使用cron表達(dá)式來指定定時(shí)任務(wù)的執(zhí)行時(shí)間點(diǎn), 即從0秒開始, 每隔10秒鐘執(zhí)行一次, 現(xiàn)在我們再加一個(gè)定時(shí)任務(wù):
@Component public class SecondScheduledTaskDemo { private static final Logger logger = LoggerFactory.getLogger(ScheduledTaskDemo.class); @Scheduled(cron = "0/10 * * * * *") public void second() { logger.info("Second scheduled task is starting... ..."); logger.info("Second scheduled task is ending... ..."); } }
現(xiàn)在再啟動(dòng)SpringBoot應(yīng)用, 再看log:
注意log中定時(shí)任務(wù)執(zhí)行的時(shí)間點(diǎn), 第二個(gè)定時(shí)任務(wù)原本應(yīng)該每隔10秒鐘執(zhí)行一次, 但是從23:12:20到23:13:55, 本該執(zhí)行4次, 確只執(zhí)行了2次.
難道是cron表達(dá)式不對?
No.
為了找到原因, 我們從 @Scheduled 注解的源碼開始找:
* * <p>Processing of {@code @Scheduled} annotations is performed by * registering a {@link ScheduledAnnotationBeanPostProcessor}. This can be * done manually or, more conveniently, through the {@code <task:annotation-driven/>} * element or @{@link EnableScheduling} annotation. *
劃重點(diǎn), 每一個(gè)有 @Scheduled 注解的方法都會被注冊為一個(gè)ScheduledAnnotationBeanPostProcessor, 再接著往下看ScheduledAnnotationBeanPostProcessor:
/** * Set the {@link org.springframework.scheduling.TaskScheduler} that will invoke * the scheduled methods, or a {@link java.util.concurrent.ScheduledExecutorService} * to be wrapped as a TaskScheduler. * <p>If not specified, default scheduler resolution will apply: searching for a * unique {@link TaskScheduler} bean in the context, or for a {@link TaskScheduler} * bean named "taskScheduler" otherwise; the same lookup will also be performed for * a {@link ScheduledExecutorService} bean. If neither of the two is resolvable, * a local single-threaded default scheduler will be created within the registrar. * @see #DEFAULT_TASK_SCHEDULER_BEAN_NAME */ public void setScheduler(Object scheduler) { this.scheduler = scheduler; }
重點(diǎn)來了, 注意這句話:
這句話意味著, 如果我們不主動(dòng)配置我們需要的 TaskScheduler, SpringBoot 會默認(rèn)使用一個(gè)單線程的scheduler來處理我們用 @Scheduled 注解實(shí)現(xiàn)的定時(shí)任務(wù), 到此我們剛才的問題就可以理解了:
23:12:20, 第一個(gè)定時(shí)任務(wù)在線程pool-1-thread-1開始執(zhí)行, 由于我們沒有配置scheduler, 目前這個(gè)線程池pool-1里只有一個(gè)線程, 在打印了starting日志之后, 這個(gè)線程開始sleep;第二個(gè)定時(shí)任務(wù)也準(zhǔn)備執(zhí)行, 但是線程池已經(jīng)沒有多余線程了, 只能等待.
23:12:30, 第一個(gè)定時(shí)任務(wù)還在sleep, 第二個(gè)定時(shí)任務(wù)還在等待.
23:12:35, 第一個(gè)定時(shí)任務(wù)sleep結(jié)束, 打印ending日志并結(jié)束, 此時(shí)線程池空閑, 第二個(gè)定時(shí)任務(wù)從等待狀態(tài)直接開始執(zhí)行, 執(zhí)行結(jié)束之后, 線程池空閑.
23:12:40, 線程池空閑, 第一個(gè)定時(shí)任務(wù)執(zhí)行, 打印starting日志, 開始sleep.
搞清楚這個(gè)流程之后, 解決這個(gè)問題就很簡單了.
根據(jù)剛才注釋的描述, 我們只需要提供一個(gè)滿足我們需要的 TaskScheduler 并注冊到context中就可以了.
@Configuration public class ScheduledTaskConfiguration implements SchedulingConfigurer { /** * Callback allowing a {@link TaskScheduler * TaskScheduler} and specific {@link Task Task} * instances to be registered against the given the {@link ScheduledTaskRegistrar} * * @param taskRegistrar the registrar to be configured. */ @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(2); taskScheduler.initialize(); taskRegistrar.setTaskScheduler(taskScheduler); } }
上面的代碼提供了一個(gè)線程池大小為2的taskScheduler, 現(xiàn)在再啟動(dòng)下SpringBoot看看效果.
可以看到, 當(dāng)線程池里有兩個(gè)線程的時(shí)候, 這兩個(gè)定時(shí)任務(wù)各自按照預(yù)定的時(shí)間進(jìn)行觸發(fā), 互不影響了.
“如何解決springboot定時(shí)任務(wù)@Scheduled執(zhí)行多次的問題”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。