Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Scheduled Task - Graceful Shutdown

I have a Spring-Boot application with a bean running a scheduled task at about 1 minute intervals, and this bean has a @PreDestroy method.

Is there a solution for allowing a task which is currently being executed to complete - or at least given some time to complete - before the life cycle reaches the pre-destroy phase?

like image 485
user1491636 Avatar asked Apr 27 '17 17:04

user1491636


People also ask

How do I gracefully shutdown Spring services?

In the Spring Boot Document, they said that 'Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. ' When I click ctrl+c on the shell command, the application can be shutdown gracefully.

How do I turn off spring boot scheduler?

Canceling the Scheduled Future. Another way to stop the scheduler would be manually canceling its Future. In the cases with multiple scheduler tasks, then we can maintain the Future map inside of the custom scheduler pool but cancel the corresponding scheduled Future based on scheduler class.

What is ThreadPoolTaskScheduler?

ThreadPoolTaskScheduler ThreadPoolTaskScheduler is well suited for internal thread management, as it delegates tasks to the ScheduledExecutorService and implements the TaskExecutor interface – so that single instance of it is able to handle asynchronous potential executions as well as the @Scheduled annotation.


3 Answers

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
like image 51
GokcenG Avatar answered Oct 05 '22 00:10

GokcenG


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.

like image 33
Matej Marconak Avatar answered Oct 05 '22 00:10

Matej Marconak


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

 @Bean
  public ThreadPoolTaskScheduler setSchedulerToWait(ThreadPoolTaskScheduler threadPoolTaskScheduler){
   threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
   return threadPoolTaskScheduler;
 }
like image 39
pvpkiran Avatar answered Oct 05 '22 01:10

pvpkiran