In Celery, how do I run a task, and then have that task run another task, and keep it going?
#tasks.py
from celery.task import Task
class Randomer(Task):
def run(self, **kwargs):
#run Randomer again!!!
return random.randrange(0,1000000)
>>> from tasks import Randomer
>>> r = Randomer()
>>> r.delay()
Right now, I run the simple task. And it returns a random number. But, how d开发者_开发技巧o I make it run another task , inside that task?
You can call other_task.delay()
from inside Randomer.run
; in this case you may want to set Randomer.ignore_result = True
(and other_task.ignore_result
, and so on).
Remember that celery tasks delay
returns instantly, so if you don't put any limit or wait time on the nested calls (or recursive calls), you can reach meltdown pretty quickly.
Instead of recursion or nested tasks, you should consider an infinite loop to avoid stack overflow (no pun intended).
from celery.task import Task
class Randomer(Task):
def run(self, **kwargs):
while True:
do_something(**kwargs)
time.sleep(600)
You can chain subtasks as described here: http://docs.celeryproject.org/en/latest/userguide/canvas.html#chains
精彩评论