I need to cancel Spring timer execution or at least change the execution frequency based on some conditions. Was using both org.springframework.scheduling.quartz.SimpleTriggerBean
and org.springframework.scheduling.timer.ScheduledTimerTask
. Cannot find the way how to do it.
NOTE: This is for Spring 3.0+
Use a
TaskScheduler
service, such as aTimerManagerTaskScheduler
orThreadPoolTaskScheduler
.Schedule your task by calling some
TaskScheduler.schedule*()
method and store the returningScheduledFuture
.When you want to cancel execution, invoke
ScheduledFuture.cancel()
. That will stop further invocations of your task. At this time, you can reschedule if you want by callingTaskScheduler.schedule*()
for your task with different parameters.
<bean>
element and inject it wherever you want to use it –
Hazing cancel()
method is mayInterruptIfRunning –
Turnery This is by far not the best solution but if you can't come up with anything else you could always use a boolean that would be checked each time the event is fired and if the boolean is false the run method of the timertask should immediately terminate.
The solution is to assign an id to the org.springframework.scheduling.timer.TimerFactoryBean and then retrieve this bean from the application, cast it to Timer and call cancel method on that object.
<task:scheduler id="myScheduler" />
Then you can get myScheduler and cancel()
. –
Electrical © 2022 - 2024 — McMap. All rights reserved.