I am currently testing Django with Celery.
A periodic task is setup with a crontab to run the following task 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
The model:
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'
Now I would like to be able to access the state of the current or last task. With Django shell, I can obtain the following:
>>> 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>}
However, I cannot access the add task from this, neither its state. Calling the task by its name does not work either:
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'
So how can I access the state of the current task assigned to the cron? I can see it from the admin through Home › Djcelery › Tasks, but how can I get that from the code?
Many thanks!
From 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}]}
Source: http://celery.readthedocs.org/en/latest/userguide/workers.html#dump-of-currently-executing-tasks