The 芹菜文档 http://celery.readthedocs.org/en/latest/userguide/tasks.html#avoid-launching-synchronous-subtasks表明让任务等待其他任务的结果是一个坏主意……但是建议的解决方案(参见“好”标题)还有一些不足之处。具体来说,没有明确的方法将子任务的结果返回给调用者(而且,这有点难看)。
那么,有什么方法可以“链接”作业,以便调用者获得最终作业的结果吗?例如,要使用add
例子:
>>> add3 = add.subtask(args=(3, ))
>>> add.delay(1, 2, callback=add3).get()
6
或者,可以返回 Result 的实例吗?例如:
@task
def add(x, y, callback=None):
result = x + y
if callback:
return subtask(callback).delay(result)
return result
这将使链中“最终”作业的结果可以通过简单的方式检索:
result = add(1, 2, callback=add3).delay()
while isinstance(result, Result):
result = result.get()
print "result:", result
你可以用芹菜链来做。看https://celery.readthedocs.org/en/latest/userguide/canvas.html#chains https://celery.readthedocs.org/en/latest/userguide/canvas.html#chains
@task()
def add(a, b):
time.sleep(5) # simulate long time processing
return a + b
连锁工作:
# import chain from celery import chain
# the result of the first add job will be
# the first argument of the second add job
ret = chain(add.s(1, 2), add.s(3)).apply_async()
# another way to express a chain using pipes
ret2 = (add.s(1, 2) | add.s(3)).apply_async()
...
# check ret status to get result
if ret.status == u'SUCCESS':
print "result:", ret.get()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)