How to cancel Spring timer execution

Deadly 提交于 2019-11-29 18:55:28

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/13868323/how-to-cancel-spring-timer-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!