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) # FalseIt 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.
What an aborted task looks like
Section titled “What an aborted task looks like”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 was when you aborted it
Section titled “Where the task was when you aborted it”| Where the task is | What abort does |
|---|---|
| Waiting on a delay or schedule | Dropped from the delayed set and finalized immediately. |
| Queued for pickup | The next worker to reach it skips it instead of running it. |
| Running | The 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.
Sync tasks can’t be interrupted
Section titled “Sync tasks can’t be interrupted”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
CancelledErrorand 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.
App-level access
Section titled “App-level access”With a task id but no Job handle:
await app.abort(task_id)Made bytay.dev