136

I have been reading the doc and searching but cannot seem to find a straight answer:

Can you cancel an already executing task? (as in the task has started, takes a while, and half way through it needs to be cancelled)

I found this from the doc at Celery FAQ

>>> result = add.apply_async(args=[2, 2], countdown=120)
>>> result.revoke()

But I am unclear if this will cancel queued tasks or if it will kill a running process on a worker. Thanks for any light you can shed!

9 Answers 9

254

revoke cancels the task execution. If a task is revoked, the workers ignore the task and do not execute it. If you don't use persistent revokes your task can be executed after worker's restart.

https://docs.celeryq.dev/en/stable/userguide/workers.html#worker-persistent-revokes

revoke has an terminate option which is False by default. If you need to kill the executing task you need to set terminate to True.

>>> from celery.task.control import revoke
>>> revoke(task_id, terminate=True)

https://docs.celeryq.dev/en/stable/userguide/workers.html#revoke-revoking-tasks

Sign up to request clarification or add additional context in comments.

9 Comments

Does this work in a distributed env? I mean if I have workers on multiple machines that are executing tasks. Does celery keep track of which machine the task is executing on?
It does. The communication with workers takes place via the broker.
result.revoke(terminate=True) should do the same thing as revoke(task_id, terminate=True)
Also, using the terminate option is "a last resort for administrators", as per recent Celery docs. You run the risk of terminating another task which has recently started on that worker.
It doesn't work, >>> from proj.celery import app <br> >>> app.control.revoke(task_id) This works only
|
62

In Celery 3.1, the API of revoking tasks is changed.

According to the Celery FAQ, you should use result.revoke:

>>> result = add.apply_async(args=[2, 2], countdown=120)
>>> result.revoke()

or if you only have the task id:

>>> from proj.celery import app
>>> app.control.revoke(task_id)

Comments

46

@0x00mh's answer is correct, however recent celery docs say that using the terminate option is "a last resort for administrators" because you may accidentally terminate another task which started executing in the meantime. Possibly a better solution is combining terminate=True with signal='SIGUSR1' (which causes the SoftTimeLimitExceeded exception to be raised in the task).

4 Comments

This solution worked very well for me. When SoftTimeLimitExceeded is raised in my task, my custom cleanup logic (implemented via try/except/finally) is invoked. This is much better, in my view, than what AbortableTask offers (docs.celeryproject.org/en/latest/reference/…). With the latter, you need a database result backend and you have to manually and repeatedly check the status of an ongoing task to see if it's been aborted.
How is this better, as far I understand if there is any other task picked up by the process, its gonna be stopped anyway, just different exception will be thrown.
If I use worker_prefetch_multiplier = 1 since I just have a few long running tasks the terminate should be fine - since no other tasks will be effected by terminating - did I get this correct? @spicyramen
SoftTimeLimitExceeded inherits from Exception rather than BaseException This causes issues when SIGUSR1 is sent to a task that happens to be executing code inside a general Exception try-except block. The approach I used was using SIGUSR2 and an exception inheriting from BaseException I would like to edit this answer to include that approach, but SO currently has "too many pending edits"
12

You define celery app with broker and backend something like :

from celery import Celery
celeryapp = Celery('app', broker=redis_uri, backend=redis_uri)

When you run send task it return unique id for task:

task_id = celeryapp.send_task('run.send_email', queue = "demo")

To revoke task you need celery app and task id:

celeryapp.control.revoke(task_id, terminate=True)

1 Comment

the only answer works for me
9

Per the 5.2.3 documentation, the following command can be run:

    celery.control.revoke(task_id, terminate=True, signal='SIGKILL')

where celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])

Link to the doc: https://docs.celeryq.dev/en/stable/reference/celery.app.control.html?highlight=revoke#celery.app.control.Control.revoke

Comments

6

In addition, unsatisfactory, there is another way(abort task) to stop the task, but there are many unreliability, more details, see: http://docs.celeryproject.org/en/latest/reference/celery.contrib.abortable.html

1 Comment

This seems to be the best way to do it when using the 'threads' pool, as celery.control.revoke(task_id, terminate=True, signal='SIGKILL') does not work.
2
from celery.app import default_app

revoked = default_app.control.revoke(task_id, terminated=True, signal='SIGKILL')
print(revoked)

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
2
from celery.result import AsyncResult
task = AsyncResult(task_id)
task.revoke()

2 Comments

Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?
Thanks! this was the only one that works for me!
1

See the following options for tasks: time_limit, soft_time_limit (or you can set it for workers). If you want to control not only time of execution, then see expires argument of apply_async method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.