[英]How to stop jobs scheduled using spring task
I have implemented a sample spring scheduled task, with an applicationContext as follows, 我已经使用applicationContext实现了一个示例spring计划任务,如下所示,
<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? 如何停止此计划方法?
Inject the ThreadPoolTaskScheduler
into another bean, and invoke shutdown()
. 将
ThreadPoolTaskScheduler
注入另一个bean,并调用shutdown()
。 If that isn't acceptable, you could configure the cron
bean to accept a flag. 如果这是不可接受的,您可以将
cron
bean配置为接受标志。 For example: 例如:
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
ScheduledFuture
and call cancel()
. 防止这种情况的唯一方法是获取对
ScheduledFuture
的引用并调用cancel()
。
Depends on what you mean by "stop". 取决于你的意思“停止”。
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.
这样,您可以在运行时停止不需要的执行,运行逻辑以处理条件失败(记录,通知等)。
Non Business Condition: Externalize the chron expression to properties file or as I prefer a system variable in the JVM. 非业务条件:将chron表达式外部化为属性文件,或者我更喜欢JVM中的系统变量。 Then you can just change the property value to a 9999 scenario to stop any execution.
然后,您只需将属性值更改为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']}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.