如何停止使用@Scheduled 批注启动的计划任务? [英] How to stop a scheduled task that was started using @Scheduled annotation?

查看:83
本文介绍了如何停止使用@Scheduled 批注启动的计划任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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:使用后处理器

供应ScheduledAnnotationBeanPostProcessor 并显式调用 postProcessBeforeDestruction(Object bean, String beanName),用于调度应该被阻止.

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 的调度不得不停止时,您可以查找映射以获取相应的 Future 并明确取消它.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆