Skip to content

Cancellation

Simon Taddiken edited this page Aug 28, 2016 · 1 revision

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.

Cancelling a scheduled method

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);
    }
}

Implications and Implementation note

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:

  1. RunnableBuilder.createLockedRunnableStack creates a Runnable which delegates to another Runnable but blocks the execution until it has been explictly unblocked.
  2. This Runnable is submitted to the scheduler
  3. The returned ScheduledFuture will be set to the ScheduledContext
  4. The Runnable created in step 1 is unblocked

See the implementations of the existing trigger strategies for some examples.