Skip to content
Advertisement

How to stop a scheduled task that was started using @Scheduled annotation?

I have created a simple scheduled task using Spring Framework’s @Scheduled annotation.

JavaScript

Now I want to stop this task, when no longer needed.

I know there could be one alternative to check one conditional flag at the start of this method, but this will not stop execution of this method.

Is there anything Spring provides to stop @Scheduled task ?

Advertisement

Answer

Option 1: Using a post processor

Supply ScheduledAnnotationBeanPostProcessor and explicitly invoke postProcessBeforeDestruction(Object bean, String beanName), for the bean whose scheduling should be stopped.


Option 2: Maintaining a map of target beans to its Future

JavaScript

When the scheduling for a bean has to be stopped, you can lookup the map to get the corresponding Future to it and explicitly cancel it.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement