如何停止使用@Scheduled注释启动的计划任务? [英] How to stop a scheduled task that was started using @Scheduled annotation?
问题描述
我使用Spring Framework的 @Scheduled
注释。
I have created a simple scheduled task using Spring Framework's @Scheduled
annotation.
@Scheduled(fixedRate = 2000)
public void doSomething() {}
现在我想在不再需要的时候停止这个任务。
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.
是否有任何Spring提供停止 @Scheduled
任务?
Is there anything Spring provides to stop @Scheduled
task ?
推荐答案
选项1:使用后处理器
供应 ScheduledAnnotation BeanPostProcessor
并显式调用 postProcessBeforeDestruction(Object bean,String beanName)
,对于应该停止其计划的bean。
Option 1: Using a post processor
Supply ScheduledAnnotationBeanPostProcessor
and explicitly invoke postProcessBeforeDestruction(Object bean, String beanName)
, for the bean whose scheduling should be stopped.
private final Map<Object, ScheduledFuture<?>> scheduledTasks =
new IdentityHashMap<>();
@Scheduled(fixedRate = 2000)
public void fixedRateJob() {
System.out.println("Something to be done every 2 secs");
}
@Bean
public TaskScheduler poolScheduler() {
return new CustomTaskScheduler();
}
class CustomTaskScheduler extends ThreadPoolTaskScheduler {
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, period);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);
return future;
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, startTime, period);
ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);
return future;
}
}
当必须停止bean的调度时,您可以查找地图以获取相应的 未来
并明确取消它。
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.
这篇关于如何停止使用@Scheduled注释启动的计划任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!