java 如何停止使用 spring 任务安排的作业

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12692083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:50:38  来源:igfitidea点击:

How to stop jobs scheduled using spring task

javaspring

提问by witek010

I have implemented a sample spring scheduled task, with an applicationContext as follows,

我已经实现了一个示例 spring 计划任务,其 applicationContext 如下,

<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="cron" method="show" cron="0/10 * * * * ?"/>
    <task:scheduled ref="cron" method="show2" cron="0/15 * * * * ?"/>
</task:scheduled-tasks>

<task:scheduler id="myScheduler" pool-size="10"/>

How can I stop this schedule method?

我怎样才能停止这种调度方法?

回答by David Grant

Inject the ThreadPoolTaskSchedulerinto another bean, and invoke shutdown(). If that isn't acceptable, you could configure the cronbean to accept a flag. For example:

将 注入ThreadPoolTaskScheduler到另一个 bean 中,然后调用shutdown(). 如果这不可接受,您可以将cronbean配置为接受标志。例如:

public class Job() {
    private final AtomicBoolean stop = new AtomicBoolean(false);

    public void show() {
        if (stop.get()) {
            return;
        }
        ...
    }

    public void stop() {
        stop.set(true);
    }
}

Note that this won't remove the job from the scheduler. The only way to prevent that would be to obtain a reference to the ScheduledFutureand call cancel().

请注意,这不会从调度程序中删除作业。防止这种情况的唯一方法是获取对ScheduledFuture和 调用的引用cancel()

回答by haju

Depends on what you mean by "stop".

取决于你所说的“停止”是什么意思。

  1. Business Condition Stop:Stop as result of a business condition, you should have those conditions evaluated in your methods and just simply not execute the code. This way you can stop unwanted execution at runtime, run your logic to handle the condition fail (logging,notification,etc) as a result.

  2. Non Business Condition:Externalize the chron expression to properties file or as I prefer a system variable in the JVM. Then you can just change the property value to a 9999 scenario to stop any execution.

  1. 业务条件停止:作为业务条件的结果停止,您应该在您的方法中评估这些条件并且只是不执行代码。通过这种方式,您可以在运行时停止不需要的执行,运行您的逻辑来处理失败的情况(日志记录、通知等)。

  2. 非业务条件:将 chron 表达式外部化到属性文件或因为我更喜欢 JVM 中的系统变量。然后您可以将属性值更改为 9999 方案以停止任何执行。

System Variable Example.

系统变量示例。

<task:scheduled-tasks scheduler="myScheduler">
<task:scheduled ref="cron" method="show" cron="#{systemProperties['chron1']}"/>
<task:scheduled ref="cron" method="show2" cron="#{systemProperties['chron2']}"/>