ray.cancel#

ray.cancel(ray_waitable: ray._raylet.ObjectRef.~R | ray._raylet.ObjectRefGenerator.~R, *, force: bool = False, recursive: bool = True) None[source]#

Cancels a task.

Cancel API has a different behavior depending on if it is a remote function (Task) or a remote Actor method (Actor Task).

Task:

If the specified Task is pending execution, it is cancelled and not executed. If the Task is currently executing, the behavior depends on the force flag. When force=False, a KeyboardInterrupt is raised in Python and when force=True, the executing Task immediately exits. If the Task is already finished, nothing happens.

Cancelled Tasks aren’t retried. max_task_retries aren’t respected.

Calling ray.get on a cancelled Task raises a TaskCancelledError if the Task has been scheduled or interrupted. It raises a WorkerCrashedError if force=True.

If recursive=True, all the child Tasks and Actor Tasks are cancelled. If force=True and recursive=True, force=True is ignored for child Actor Tasks.

Actor Task:

If the specified Task is pending execution, it is cancelled and not executed. If the Task is currently executing, the behavior depends on the execution model of an Actor. If it is a regular Actor or a threaded Actor, Ray sets a cancellation flag that can be checked via ray.get_runtime_context().is_canceled() within the task body. This allows for graceful cancellation by periodically checking the cancellation status. If it is an async Actor, Ray cancels a asyncio.Task. The semantic of cancellation is equivalent to asyncio’s cancellation. https://docs.python.org/3/library/asyncio-task.html#task-cancellation Note: is_canceled() is not supported for async actors and will raise a RuntimeError. If the Task has finished, nothing happens.

Only force=False is allowed for an Actor Task. Otherwise, it raises ValueError. Use ray.kill(actor) instead to kill an Actor.

Cancelled Tasks aren’t retried. max_task_retries aren’t respected.

Calling ray.get on a cancelled Task raises a TaskCancelledError if the Task has been scheduled or interrupted.

If recursive=True, all the child Tasks and actor Tasks are cancelled.

Parameters:
  • ray_waitableObjectRef and ObjectRefGenerator returned by the task that should be canceled.

  • force – Whether to force-kill a running task by killing the worker that is running the task.

  • recursive – Whether to try to cancel tasks submitted by the task specified.