首页 > 解决方案 > 如何查询芹菜任务的状态

问题描述

使用这段代码,是否可以查询workerstate是在state=1还是state=2?

from celery import Celery
import time

#celery -A CeleryTask worker --loglevel=info

app = Celery("CeleryTask", backend="redis://localhost", broker="redis://localhost")


@app.task
def train():
    for i in range(100):
        if i<5:
            state=1

        else:
            state=2
        time.sleep(10)

    return "hallo"

if __name__ == '__main__':
    result = train.delay()
  

标签: pythonpython-3.xcelerycelery-task

解决方案


Celery 非常棒,它为您提供了创建自己的自定义状态并使用update_state()方法更新它们的机制。

从(链接的)文档中:

@app.task(bind=True)
def upload_files(self, filenames):
    for i, file in enumerate(filenames):
        if not self.request.called_directly:
            self.update_state(state='PROGRESS',
                meta={'current': i, 'total': len(filenames)})

在您的情况下,您所要做的就是调用 update_state() ,meta={"state":X}其中 X 为 1 或 2 ...


推荐阅读