Client: revoking tasks
A Celery client cannot revoke a task of this runner on its own: revoke() broadcasts to
workers, and there are none. celery_cloud.client.install makes it work through the
result backend. It is optional and the only place where the client needs the
celery-cloud package (it only needs boto3, no runner settings).
"""Revoke a task: the optional helper that needs the runner's help."""
import time
from celery_app import add, app, long_job
from celery_cloud.client import install
# Once, after configuring the app: result.revoke() / app.control.revoke() now write
# the revocation to the result backend, where the runner reads it
install(app)
# 1. A task that has not started never starts
held = add.apply_async(args=(1, 2), countdown=60) # held by the runner until it is due
held.revoke()
time.sleep(2)
print(held.state) # REVOKED
# 2. A running task is only flagged: it stops if its code looks at is_revoked()
job = long_job.apply_async(args=(20,))
time.sleep(3)
job.revoke() # terminate=True is accepted, but a running task is never killed
print(job.get(timeout=60)) # stopped after 6 steps because it was revoked
How it works
install(app) replaces app.control.revoke, so result.revoke() and
app.control.revoke(task_id) both work. It reads the Region and table from the app’s
result_backend (dynamodb://@region/table) and the result_serializer.
If the task has not started the helper creates its item with
REVOKEDand arevokedflag. When the message arrives the runner finds it and skips the task:result.stateisREVOKEDandget()raisesTaskRevokedError.If the task already exists (running or finished) only the flag is set. A task that checks
self.is_revoked()between its steps can stop; nothing interrupts a running function, andterminate=True/signal=are accepted but do not kill anything.
Revoking before the task is queued is also possible: revoke by id, then send the message.
Permissions
The identity of the client also needs dynamodb:PutItem and dynamodb:UpdateItem on
the table (IAM roles and permissions).
Without install
Everything else keeps working. result.revoke() is then accepted but has no effect,
except that Celery may try to reach a broadcast channel and wait for a timeout.