0

So basically my app does some processing of stuff in intervals every 1 second. I have to implement a SIGTERM signal to my app but I have to let the stuff that is currently being processed in app to FINISH and then the app can terminate. Therefore I'm looking for something like a try{}catch{} but for SIGTERM, I would do a sleep for few seconds and then let the SIGTERM terminate the app, is there something like that?

As far as I know @PreDestroy closes whole context and then leaves one bean annotated with it, executes it and then destroys.

Also the addShutdownHook() is a method to be run when shutting down app, but I just want my main processing to finish and then shutdown everything.

Is there a way to do it?

essaPL
  • 11
  • 2
  • How do you schedule the async process that runs every 1 second? Do you use `@Scheduled` annotation? – Spyros Palaiokostas Jul 19 '23 at 11:11
  • Yes, it's @Scheduled and runs every 1 second, i'd just make a flag on start of this method and set it when catching a SIGTERM so no new data is being processed, but i still have to process the already processing data when receiving SIGTERM. – essaPL Jul 19 '23 at 11:53

1 Answers1

0

The scheduled tasks are handled by Spring's TaskExecutor you can configure it to set a max wait time before termination and set a flag to wait for the task on shutdown.

You can configure the TaskExecutor by creating a custom ThreadPoolTaskExecutor bean.

For example:

@Bean
public TaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
    taskExecutor.initialize();
    return taskExecutor;
}

Additionally, you can set the option for max wait time:

taskExecutor.setAwaitTerminationSeconds(60);

the reason behind this:

Though we've configured to wait for ongoing and queued-up tasks to complete, Spring continues with the shutdown of the rest of the container. This could release resources needed by our task executor and cause the tasks to fail.

You can read more here