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, the execution isn’t cancelled. Actor Tasks cannot be interrupted because Actors have states. 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 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. Also note that only async actor tasks can be 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.