优雅地停止芹菜任务

ora*_*nge 3 python celery celery-task django-celery

我想优雅地退出芹菜任务(即不是通过电话revoke(celery_task_id, terminate=True)).我以为我会向设置标志的任务发送消息,以便任务函数可以返回.与任务沟通的最佳方式是什么?

小智 8

你也可以使用AbortableTask.我认为这是优雅地停止任务的最佳方式.

http://docs.celeryproject.org/en/latest/reference/celery.contrib.abortable.html

from celery.contrib.abortable import AbortableTask
from proj.celery import app

@app.task(bind=True, base=AbortableTask)
def abortable_task(self):
    while not self.is_aborted():
       print 'I am running'

    print 'I was aborted!'
Run Code Online (Sandbox Code Playgroud)

如果您将ID任务保存在某个地方,您可以随时调用它.

from celery.contrib.abortable import AbortableAsyncResult

abortable_task = AbortableAsyncResult(task_id)
abortable_task.abort()
Run Code Online (Sandbox Code Playgroud)


Cai*_*von 7

为此使用信号.芹菜revoke 正确的选择; 它默认使用SIGTERM,但如果您愿意,可以使用参数指定另一个signal.

只需在任务(使用signal模块)中为它设置一个信号处理程序,即可优雅地终止任务.