In my sping boot application i have several Cron jobs that should be able to finish running before the application shuts down. I'm using a TaskSchedulerCustomizer
bean to configure spring's default task scheduler to wait for tasks to complete on shutdown.
@Bean //https://stackoverflow.com/questions/43664259/spring-scheduled-task-graceful-shutdown
public TaskSchedulerCustomizer taskSchedulerCustomizer() { //Dit laat Spring het TaskScheduler object zelf aanmaken en customized het alleen.
return taskScheduler -> {
taskScheduler.setPoolSize(CORE_THREAD_POOL_SIZE);
taskScheduler.setThreadNamePrefix("CronJob-");
taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
taskScheduler.setAwaitTerminationSeconds(AWAIT_TERMINATION_SECONDS);
};
}
Despite setting setWaitForTasksToCompleteOnShutdown()
to true
the graceful shutdown of Spring boot still interrupts my running cronjob tasks. I've also added the following settings to my application.properties
:
spring.task.scheduling.shutdown.await-termination=true
spring.task.scheduling.shutdown.await-termination-period=30s
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=30s
But these are all ignored as well. I also called initialize()
on the taskScheduler
in after setting setWaitForTasksToCompleteOnShutdown()
to true to see if that would help. But didn't help either.
So i've pretty much tried everything to get spring to respect my running cronjob tasks. Is there anything left i could try?
Here's the cronjob code that i used for testing
@Scheduled(cron = "* * * * * *")
public void schedule() throws InterruptedException {
log.info("starting dummy scheduler");
Thread.sleep(10000);
log.info("ending dummy scheduler");
}
I've managed to solve the problem by looking at the code snippets from this SO question.
When I create my own TaskScheduler
bean and then register it using the overidden configureTasks
method of an SchedulingConfigurer
implementation everything works. Its very strange that it only works this way and not with a TaskSchedulerCustomizer
bean or with the aforementioned application.properties properties. Heres the code:
@EnableScheduling
public class ContextSchedulingConfiguration implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(securitytaskScheduler());
}
@Bean
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler= new ThreadPoolTaskScheduler();
taskScheduler.setAwaitTerminationSeconds(120);
taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
taskScheduler.setPoolSize(2);
taskScheduler.setThreadNamePrefix("XXXXXXXXX");
return taskScheduler;
}
}
Its a paste from this SO question