Python + Celery:链接工作?

Dav*_*ver 32 python celery

芹菜文件表明,这是一个坏主意,有任务等待的其他任务的结果.但建议的解决方案(见"好"标题)离开是可喜爱的东西.具体来说,没有明确的方法将子任务的结果返回给调用者(同样,它有点难看).

那么,有没有"链接"工作的方式,所以调用者得到最终工作的结果?例如,要使用add示例:

>>> add3 = add.subtask(args=(3, ))
>>> add.delay(1, 2, callback=add3).get()
6
Run Code Online (Sandbox Code Playgroud)

或者,返回Result的实例是否可以?例如:

@task
def add(x, y, callback=None):
    result = x + y
    if callback:
        return subtask(callback).delay(result)
    return result
Run Code Online (Sandbox Code Playgroud)

这将使链中"最终"工作的结果可以通过简单的方式重新获得:

result = add(1, 2, callback=add3).delay()
while isinstance(result, Result):
    result = result.get()
print "result:", result
Run Code Online (Sandbox Code Playgroud)

ax0*_*03d 32

你可以用芹菜链做到这一点.请参阅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
Run Code Online (Sandbox Code Playgroud)

链接工作:

# 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()
Run Code Online (Sandbox Code Playgroud)

  • `celery` 文档说用 `.delay().get()` 调用多个任务是不好的,他们提供了一个[替代](https://docs.celeryproject.org/en/stable/userguide/tasks)。 html#avoid-launching-synchronous-subtasks),但他们没有解释**为什么**替代方案更好。为什么链接的替代技术更好?链接方法是否只使用超时,从而避免可能的死机(即“.delay().get(timeout=1.0)”)? (3认同)