In Celery, how do I run a task, and then have that task run another task, and keep it going?

谁说胖子不能爱 提交于 2019-12-09 07:08:41

问题


#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 do I make it run another task , inside that task?


回答1:


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)



回答2:


You can chain subtasks as described here: http://docs.celeryproject.org/en/latest/userguide/canvas.html#chains



来源:https://stackoverflow.com/questions/4552854/in-celery-how-do-i-run-a-task-and-then-have-that-task-run-another-task-and-ke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!