I have implemented a sample spring scheduled task, with an applicationContext as follows,
<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?
Another way to stop the scheduler would be manually canceling its Future. In the cases with multiple scheduler tasks, then we can maintain the Future map inside of the custom scheduler pool but cancel the corresponding scheduled Future based on scheduler class.
The method is stop(long executionId) You would have to use JobExplorer to find the correct executionId to stop. Also from within a job flow config you can configure a job to stop after a steps execution based on exit status (see https://docs.spring.io/spring-batch/trunk/reference/html/configureStep.html#stopElement).
In order to cancel the Timer Task in Java, we use the java. util. TimerTask. cancel() method.
Scheduling is not enabled by default. We explicitly enable scheduling by adding the @EnableScheduling annotation to a Spring configuration class. We can make the scheduling conditional on a property so that we can enable and disable scheduling by setting the property.
Inject the ThreadPoolTaskScheduler
into another bean, and invoke shutdown()
. If that isn't acceptable, you could configure the cron
bean to accept a flag. 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()
.
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. Then you can just change the property value to a 9999 scenario to stop any execution.
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']}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With