1

I am having a spring batch application and it contains multiple jobs. I need to shutdown the application gracefully when sending the KILL signal from the command line. It should wait until the currently running job completes. (In the mean time, it should not accept new jobs from scheduler).

This is my Spring Boot Application configuration.

@SpringBootApplication
@EnableScheduling
@EnableBatchProcessing
public class SpringBootBatchExampleApplication {

    public static void main(String[] args) {

        SpringApplicationBuilder app = new SpringApplicationBuilder(SpringBootBatchExampleApplication.class)
                .web(WebApplicationType.NONE);
        app.registerShutdownHook(true);
        app.build().addListeners(new ApplicationPidFileWriter("/shutdown.pid"));
        app.run(args);
    }

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

    @PreDestroy
    public void onDestroy() throws Exception{
        Thread.sleep(5000);
    }
}

Whenever i send the application kill in the middle of job execution, signal it calls the destroy method and waits for 5 seconds.

After it starts to resume the job execution and suddenly terminate the whole process with some exception due to the ApplicationContext is already closed. So the current job cannot be executed further.

Is there any way to hold the application context close/destroy until the pending/currently running jobs get completed?

Chathuranga Tennakoon
  • 2,059
  • 1
  • 18
  • 20

0 Answers0