Cancel an already executing task with Celery?
Asked Answered
G

9

130

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!

Garnett answered 19/1, 2012 at 3:21 Comment(0)
B
242

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

Bowne answered 19/1, 2012 at 10:2 Comment(9)
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?Necessarily
It does. The communication with workers takes place via the broker.Bowne
result.revoke(terminate=True) should do the same thing as revoke(task_id, terminate=True)Watanabe
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.Orchestral
unfortunately this works only on ampq and redis docAdjective
@Adjective Why does this only work on ampq and redis?Patmos
It doesn't work, >>> from proj.celery import app <br> >>> app.control.revoke(task_id) This works onlyPigsty
From the command line, this worked like a charm using the hints from this answer. I needed to stop some actively-executing tasks that were running way longer than desired: celery -A <YOUR APP> inspect active | grep “<THE_TASK_YOU_WANT_TO_STOP>” | sed -e "s/.*id': '\([^']*\).*/\1/" | xargs celery -A <YOUR APP> control terminate KILLJunto
Have we ability to revoke and DELETE tasks not from command prompt?Lacteal
P
61

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)
Paloma answered 29/8, 2014 at 3:44 Comment(0)
O
39

@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).

Orchestral answered 14/4, 2015 at 12:38 Comment(4)
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.Dulles
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.Gliadin
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? @spicyramenHulsey
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"Recognizee
H
8

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

Heidiheidie answered 31/3, 2022 at 20:5 Comment(0)
N
7

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)
Nineteen answered 6/4, 2022 at 5:29 Comment(1)
the only answer works for mePreselector
C
5

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

Carmelinacarmelita answered 6/12, 2018 at 6:29 Comment(1)
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.Smoulder
C
2
from celery.app import default_app

revoked = default_app.control.revoke(task_id, terminated=True, signal='SIGKILL')
print(revoked)
Cicatrize answered 20/2, 2022 at 15:35 Comment(1)
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.Transferase
A
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.

Appraisal answered 19/1, 2012 at 6:40 Comment(0)
R
0
from celery.result import AsyncResult
task = AsyncResult(task_id)
task.revoke()
Rump answered 19/9, 2023 at 17:57 Comment(1)
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?Enigmatic

© 2022 - 2024 — McMap. All rights reserved.