Cancel an already executing task with Celery?

孤街醉人 提交于 2019-11-26 23:37:25
mher

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.

http://docs.celeryproject.org/en/latest/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)

http://docs.celeryproject.org/en/latest/userguide/workers.html#revoke-revoking-tasks

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)
kouk

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

simplylizz

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!