11

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.

ElderMael
  • 7,000
  • 5
  • 34
  • 53
BigWonder
  • 225
  • 1
  • 4
  • 18

3 Answers3

22

NOTE: This is for Spring 3.0+

  1. Read Spring documentation on scheduling tasks

  2. Use a TaskScheduler service, such as a TimerManagerTaskScheduler or ThreadPoolTaskScheduler.

  3. Schedule your task by calling some TaskScheduler.schedule*() method and store the returning ScheduledFuture.

  4. 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 calling TaskScheduler.schedule*() for your task with different parameters.

Klesun
  • 12,280
  • 5
  • 59
  • 52
gpeche
  • 21,974
  • 5
  • 38
  • 51
  • My beans are provisioned in the spring xml file. How I get an instance of the TaskScheduler from there? Are you saying that I need to provision it all in my Java code? – BigWonder Dec 13 '12 at 22:40
  • Just instantiate the TaskScheduler using a `` element and inject it wherever you want to use it – gpeche Dec 15 '12 at 20:48
  • Note, the boolean parameter of `cancel()` method is [mayInterruptIfRunning](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#cancel-boolean-) – Klesun Sep 13 '22 at 07:03
0

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.

TRU7H
  • 187
  • 1
  • 1
  • 10
  • That's what I actually did. This approach is definitely not preferable as I don't want to execute task again if some condition is met. – BigWonder Dec 13 '12 at 21:47
0

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.

BigWonder
  • 225
  • 1
  • 4
  • 18