witek010
witek010

Reputation: 369

How to stop jobs scheduled using spring task

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?

Upvotes: 6

Views: 12281

Answers (2)

David Grant
David Grant

Reputation: 14223

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().

Upvotes: 3

haju
haju

Reputation: 1298

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.

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']}"/>

Upvotes: 1

Related Questions