伺服器設置定時重啟「伺服器定時任務不執行」

SpringBoot:為什麼我的定時任務不執行?

在SpringBoot中可以通過@Scheduled 註解來定義一個定時任務, 但是有時候你可能會發現有的定時任務到時間了卻沒有執行,但是又不是每次都不執行,這是怎麼回事?

下面這段代碼定義了一個每隔十秒鐘執行一次的定時任務:

@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... ...");
    }
}

此時啟動SpringBoot應用, 可以在控制台看到這個定時任務每隔10秒鐘列印一條log

2017-12-21 22:20:20.832 INFO 7424 — [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8000 (http) 2017-12-21 22:20:20.859 INFO 7424 — [ main] com.example.demo.DemoApplication : Started DemoApplication in 12.134 seconds (JVM running for 14.156) 2017-12-21 22:20:30.002 INFO 7424 — [pool-1-thread-1] c.e.demo.scheduled.ScheduledTaskDemo : Scheduled task is running… … 2017-12-21 22:20:40.001 INFO 7424 — [pool-1-thread-1] c.e.demo.scheduled.ScheduledTaskDemo : Scheduled task is running… … 2017-12-21 22:20:50.002 INFO 7424 — [pool-1-thread-1] c.e.demo.scheduled.ScheduledTaskDemo : Scheduled task is running… …

但是, 一切還沒結束.

如果沒有相關log顯示, 檢查是否在入口類或者Configuration類上添加了@EnableScheduling註解

在上面的相關代碼中, 我們使用cron表達式來指定定時任務的執行時間點, 即從0秒開始, 每隔10秒鐘執行一次, 現在我們再加一個定時任務:

@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... ...");
    }

}

現在再啟動SpringBoot應用, 再看log:

2017-12-21 23:12:20.007 INFO 13208 — [pool-1-thread-1] c.e.demo.scheduled.ScheduledTaskDemo : First scheduled task is starting… … 2017-12-21 23:12:35.013 INFO 13208 — [pool-1-thread-1] c.e.demo.scheduled.ScheduledTaskDemo : First scheduled task is ending… … 2017-12-21 23:12:35.016 INFO 13208 — [pool-1-thread-1] c.e.demo.scheduled.SecondScheduledTaskDemo : Second scheduled task is starting… … 2017-12-21 23:12:35.016 INFO 13208 — [pool-1-thread-1] c.e.demo.scheduled.SecondScheduledTaskDemo : Second scheduled task is ending… … 2017-12-21 23:12:40.000 INFO 13208 — [pool-1-thread-1] c.e.demo.scheduled.ScheduledTaskDemo : First scheduled task is starting… … 2017-12-21 23:12:55.001 INFO 13208 — [pool-1-thread-1] c.e.demo.scheduled.ScheduledTaskDemo : First scheduled task is ending… … 2017-12-21 23:12:55.002 INFO 13208 — [pool-1-thread-1] c.e.demo.scheduled.SecondScheduledTaskDemo : Second scheduled task is starting… … 2017-12-21 23:12:55.002 INFO 13208 — [pool-1-thread-1] c.e.demo.scheduled.SecondScheduledTaskDemo : Second scheduled task is ending… …

注意log中定時任務執行的時間點, 第二個定時任務原本應該每隔10秒鐘執行一次, 但是從23:12:20到23:13:55, 本該執行4次, 確只執行了2次.

難道是cron表達式不對?

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.
 *

劃重點, 每一個有@Scheduled註解的方法都會被註冊為一個
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;
	}

重點來了, 注意這句話:

If neither of the two is resolvable, a local single-threaded default scheduler will be created within the registrar.

這句話意味著, 如果我們不主動配置我們需要的TaskScheduler, SpringBoot會默認使用一個單線程的scheduler來處理我們用@Scheduled註解實現的定時任務, 到此我們剛才的問題就可以理解了:

23:12:20, 第一個定時任務在線程pool-1-thread-1開始執行, 由於我們沒有配置scheduler, 目前這個線程池pool-1里只有一個線程, 在列印了starting日誌之後, 這個線程開始sleep;第二個定時任務也準備執行, 但是線程池已經沒有多餘線程了, 只能等待.

23:12:30, 第一個定時任務還在sleep, 第二個定時任務還在等待.

23:12:35, 第一個定時任務sleep結束, 列印ending日誌並結束, 此時線程池空閑, 第二個定時任務從等待狀態直接開始執行, 執行結束之後, 線程池空閑.

23:12:40, 線程池空閑, 第一個定時任務執行, 列印starting日誌, 開始sleep.

注意, 這裡也有可能執行第二個定時任務, 看CPU了.

… …

搞清楚這個流程之後, 解決這個問題就很簡單了.

根據剛才注釋的描述, 我們只需要提供一個滿足我們需要的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);
    }
}

上面的代碼提供了一個線程池大小為2的taskScheduler, 現在再啟動下SpringBoot看看效果.

2017-12-21 23:28:30.001 INFO 7972 — [TaskScheduler-1] c.e.demo.scheduled.ScheduledTaskDemo : Second scheduled task is starting… … 2017-12-21 23:28:30.001 INFO 7972 — [TaskScheduler-2] c.e.demo.scheduled.ScheduledTaskDemo : First scheduled task is starting… … 2017-12-21 23:28:30.002 INFO 7972 — [TaskScheduler-1] c.e.demo.scheduled.ScheduledTaskDemo : Second scheduled task is ending… … 2017-12-21 23:28:40.001 INFO 7972 — [TaskScheduler-1] c.e.demo.scheduled.ScheduledTaskDemo : Second scheduled task is starting… … 2017-12-21 23:28:40.001 INFO 7972 — [TaskScheduler-1] c.e.demo.scheduled.ScheduledTaskDemo : Second scheduled task is ending… … 2017-12-21 23:28:45.002 INFO 7972 — [TaskScheduler-2] c.e.demo.scheduled.ScheduledTaskDemo : First scheduled task is ending… …

可以看到, 當線程池裡有兩個線程的時候, 這兩個定時任務各自按照預定的時間進行觸發, 互不影響了.

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/252476.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-14 02:16
下一篇 2024-12-14 02:16

相關推薦

發表回復

登錄後才能評論