Spring - Scheduled Task - Graceful Shutdown

Starting from Spring Boot 2.1.0, you can use this:

@Bean
TaskSchedulerCustomizer taskSchedulerCustomizer() {
    return taskScheduler -> {
        taskScheduler.setAwaitTerminationSeconds(60);
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
    };
}

TaskSchedulerCustomizer will be used to modify configured ThreadPoolTaskScheduler

Details:

  1. ExecutorConfigurationSupport
  2. TaskSchedulerCustomizer

You need update configuration of ThreadPoolTaskScheduler. Set true for waitForJobsToCompleteOnShutdown (method setWaitForTasksToCompleteOnShutdown).

From documentation:

Set whether to wait for scheduled tasks to complete on shutdown, not interrupting running tasks and executing all tasks in the queue. Default is "false", shutting down immediately through interrupting ongoing tasks and clearing the queue. Switch this flag to "true" if you prefer fully completed tasks at the expense of a longer shutdown phase.


@Matej is right. Some thing like this should do the trick

 @Bean
  public ThreadPoolTaskScheduler setSchedulerToWait(ThreadPoolTaskScheduler threadPoolTaskScheduler){
   threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
   return threadPoolTaskScheduler;
 }