-
Notifications
You must be signed in to change notification settings - Fork 4
Cancellation
This section explains how a scheduled method can be cancelled and how cancellation is implemented.
As by the JDK API, whenever you schedule a Runnable
with a ScheduledExecutorService
, you obtain a ScheduledFuture
object as return value. This object can be used for cancelling the submitted task. In this term, cancelling means that the task will either not be run at all or never be scheduled again. Optionally, when the task is already running by the time it is cancelled the executing thread may be interrupted.
The scheduling of a method can only be cancelled from within this method by accessing the current ScheduledContext
. There is currently no possibility to cancel such a method from the outside. By injecting the context, you may call ScheduledContext.cancel(boolean)
where the boolean attributes determines whether the executing thread should be interrupted.
@Scheduled
@SimpleTrigger(2000)
public void scheduledMethod(ScheduledContext context) {
if (context.getExecutionCount() > THRESHOLD) {
context.cancel(true);
}
}
As stated above, cancelling a method is technically only possible via the ScheduledFuture
object which is obtained by submitting a task to the scheduler. In order for client code to access this object, it must be registered with the ScheduledContext
. But this implies that the first execution of the scheduled method (which, in theory, could be started immediately after submitting the task) must be blocked until it is ensured that the Future
object is set to the context object.
Thus for implementing a TriggerStrategy the following pattern is used to block the first scheduled execution until it is ensured that the Future
is registered to the context object:
-
RunnableBuilder.createLockedRunnableStack
creates aRunnable
which delegates to another Runnable but blocks the execution until it has been explictly unblocked. - This Runnable is submitted to the scheduler
- The returned
ScheduledFuture
will be set to theScheduledContext
- The Runnable created in step 1 is unblocked
See the implementations of the existing trigger strategies for some examples.