我目前正在用Celery测试Django。
使用crontab设置定期任务以运行以下任务add:
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()[&#39; extractionapp.tasks.add&#39;] Traceback(最近一次调用最后一次): 文件&#34;&#34;,第1行,in 文件&#34; /Users/antoinebrunel/seo/lib/python2.7/site-packages/celery/app/registry.py",第26行,缺失 提高自我。不注册(关键) NotRegistered:&#39; extractionapp.tasks.add&#39;
那么如何访问分配给cron的当前任务的状态?我可以通过主页> Djcelery> Tasks从管理员看到它,但我怎样才能从代码中获得它?
非常感谢!
答案 0 :(得分:2)
来自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