8

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?

user1491636
  • 2,355
  • 11
  • 44
  • 71
  • Can you please answer this ? https://stackoverflow.com/questions/74376294/how-to-gracefully-shutdown-spring-boot-app-using-configuration-and-programatical – MiGo Nov 10 '22 at 12:36

4 Answers4

18

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
GokcenG
  • 2,771
  • 2
  • 25
  • 40
6

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 Marconak
  • 1,365
  • 3
  • 20
  • 25
  • 2
    Actually, I just realized that the `@PreDestroy` is still being called prior to the task completing. I'm using a solution like this: http://stackoverflow.com/a/35017579/1491636 however I'm additionally setting the `setWaitForTasksToCompleteOnShutdown` flag to true. – user1491636 Apr 28 '17 at 15:33
2

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

 @Bean
  public ThreadPoolTaskScheduler setSchedulerToWait(ThreadPoolTaskScheduler threadPoolTaskScheduler){
   threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
   return threadPoolTaskScheduler;
 }
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
  • This solution does not work for me: ``` The dependencies of some of the beans in the application context form a cycle: ┌──->──┐ | setSchedulerToWait defined in class path resource [at/codemonkey/shutdown/scheduler/TaskExecutorConfiguration.class] └──<-──┘ ``` – Stefan Haberl Jun 09 '21 at 13:14
0

In later versions of spring boot you can also set these properties via application.properties. For example

server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=60s
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=60s
spring.task.scheduling.shutdown.await-termination=true
spring.task.scheduling.shutdown.await-termination-period=60s
João Pedro Schmitt
  • 1,046
  • 1
  • 11
  • 25