Skip to content

Aborting tasks

await job.abort() cancels a task wherever it currently is — waiting on a delay, queued for pickup, or already running on some worker.

job = await slow_report.options(delay_ms=60_000).enqueue()
if await job.abort(): # False if it already finished
result = await job.result(timeout=5)
print(result.aborted) # True
print(result.success) # False

It returns False when there is nothing left to cancel: the task already finished, or the id is unknown. Aborting twice is safe — the second call just returns False.

An aborted task ends as an ordinary failed TaskResult with the aborted flag set, so it never retries and result(timeout=) returns as soon as it settles.

result = await job.result(timeout=5)
if result.aborted:
print("cancelled")
elif not result.success:
print("failed:", result.value)

aborted is a property — not success and value == "aborted" — so an abort is easy to tell apart from a task that failed on its own.

Where the task isWhat abort does
Waiting on a delay or scheduleDropped from the delayed set and finalized immediately.
Queued for pickupThe next worker to reach it skips it instead of running it.
RunningThe worker holding it cancels it, within about a millisecond.

The first two cases are settled by a single Lua script, so the result is ready by the time abort() returns. The third goes out on a Redis pub/sub channel that every running worker subscribes to; the one holding the task cancels it and stores the aborted result.

Cancellation is asyncio cancellation, so it reaches a task at its next await.

  • Async tasks are cancelled at the next suspension point. A task that catches CancelledError and carries on will keep running.
  • Sync tasks run in a thread (see Defining tasks), and Python can’t interrupt a running thread. The worker stops waiting and reports the task aborted, but the function itself runs to completion.

If you need a sync task to stop early, have it check a flag of your own between chunks of work.

With a task id but no Job handle:

await app.abort(task_id)

Made bytay.dev