有什么区别:
r = group(some_task.s(i) for i in range(10)).apply_async()
result = r.join()
和:
r = group(some_task.s(i) for i in range(10))()
result = r.get()
Celery 文档使用了这两个示例,我看不出有任何区别。
最佳答案
简答
虽然 group
的 get
和 join
方法应该返回相同的结果,但是 get
实现了一些缓存并且可能会更有效,具体取决于您使用的后端。除非你真的需要在某些边缘情况下使用 join
,否则你应该使用 get
。
长答案
这是 GroupResult
类扩展的 celery ResultSet
类的 get
方法的源代码。
def get(self, timeout=None, propagate=True, interval=0.5,
callback=None, no_ack=True, on_message=None):
"""See :meth:`join`
This is here for API compatibility with :class:`AsyncResult`,
in addition it uses :meth:`join_native` if available for the
current result backend.
"""
if self._cache is not None:
return self._cache
return (self.join_native if self.supports_native_join else self.join)(
timeout=timeout, propagate=propagate,
interval=interval, callback=callback, no_ack=no_ack,
on_message=on_message,
)
我们首先看到的是文档字符串告诉我们查看文档的 join
方法。马上,这表明这些方法非常相似。
查看 get
方法的主体,我们可以看到它首先检查缓存值,如果已设置则返回该值。如果未找到缓存值,get
将调用 join
或 join_native
方法,具体取决于后端是否支持 native 连接。如果您发现 return
语句的格式有点困惑,这本质上是一样的:
if self.supports_native_join:
return self.join_native(timeout=timeout,
propagate=propagate,
interval=interval,
callback=callback,
no_ack=no_ack,
on_message=on_message)
else:
return self.join(timeout=timeout,
propagate=propagate,
interval=interval,
callback=callback,
no_ack=no_ack,
on_message=on_message)
join
方法的文档字符串是这样说的。
This can be an expensive operation for result store backends that must resort to polling (e.g., database). You should consider using
join_native
if your backend supports it.
因此,如果您的后端支持,您应该调用 join_native
而不是 join
。但是,如果 get
为您总结了这个逻辑,为什么还要有条件地调用一个或另一个呢?只需使用 get
即可。
关于python - celery get 和 join 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33199038/