Django with Celery:从正在进行的任务中获取状态

Django with Celery: Getting the status from an undergoing task

我目前正在使用 Celery 测试 Django。

使用 crontab 设置周期性任务以 运行 添加以下任务:

from __future__ import absolute_import

from celery import task
import time

@task
def add(x, y):
    print "Start : %s" % time.ctime()
    time.sleep(120)
    print "End : %s" % time.ctime()
    return x + y

型号:

from django.db import models
from djcelery.models import CrontabSchedule
from djcelery.models import TaskState

class Manager(models.Model):
    cron = models.ForeignKey(CrontabSchedule)

    def app_status(self):
        return self.cron.schedule.app.tasks

    app_status.admin_order_field = 'app status'

现在我希望能够访问当前或上一个任务的状态。使用 Django shell,我可以获得以下内容:

>>> import django
>>> from extractionapp.models import Manager
>>> Manager.objects.all()[0].app_status()
{'celery.chain': <@task: celery.chain of proj:0x1022f1a90>, 'celery.chord': <@task: celery.chord of proj:0x1022f1a90>, 'proj.celery.debug_task': <@task: proj.celery.debug_task of proj:0x1022f1a90>, 'celery.chunks': <@task: celery.chunks of proj:0x1022f1a90>, 'celery.chord_unlock': <@task: celery.chord_unlock of proj:0x1022f1a90>, 'celery.group': <@task: celery.group of proj:0x1022f1a90>, 'celery.backend_cleanup': <@task: celery.backend_cleanup of proj:0x1022f1a90>, 'celery.map': <@task: celery.map of proj:0x1022f1a90>, 'celery.starmap': <@task: celery.starmap of proj:0x1022f1a90>}

但是,我无法从这里访问添加任务,也无法访问它的状态。 按名称调用任务也不起作用:

Manager.objects.all()[0].app_status()['extractionapp.tasks.add'] Traceback (most recent call last): File "", line 1, in File "/Users/antoinebrunel/seo/lib/python2.7/site-packages/celery/app/registry.py", line 26, in missing raise self.NotRegistered(key) NotRegistered: 'extractionapp.tasks.add'

那么如何访问分配给 cron 的当前任务的状态?我可以通过主页 › Djcelery › 任务从管理员那里看到它,但是我如何从代码中得到它?

非常感谢!

来自 Django shell:

>>> from celery import Celery
>>> app = Celery('proj')
>>> i = app.control.inspect()
>>> i.active()
{u'celery@HeyHeyHey': [{u'args': u'[2, 2]', u'time_start': 448519.58944676, u'name': u'extractionapp.tasks.add', u'delivery_info': {u'priority': None, u'redelivered': False, u'routing_key': u'celery', u'exchange': u'celery'}, u'hostname': u'celery@HeyHeyHey', u'acknowledged': True, u'kwargs': u'{}', u'id': u'05fa4347-a222-45f3-9ee0-f3c261a21a24', u'worker_pid': 23999}]}

来源:http://celery.readthedocs.org/en/latest/userguide/workers.html#dump-of-currently-executing-tasks