【问题标题】:Retrieve task result by id in Celery在 Celery 中通过 id 检索任务结果
【发布时间】:2015-08-25 12:15:12
【问题描述】:

我正在尝试检索已完成任务的结果。 这行得通

from proj.tasks import add
res = add.delay(3,4)
res.get()
7
res.status
'SUCCESS'
res.id
'0d4b36e3-a503-45e4-9125-cfec0a7dca30'

但我想从另一个应用程序运行它。所以我重新运行 python shell 并尝试:

from proj.tasks import add
res = add.AsyncResult('0d4b36e3-a503-45e4-9125-cfec0a7dca30')
res.status
'PENDING'
res.get() # Error

如何检索结果?

【问题讨论】:

  • 您使用什么作为代理/后端?
  • 我使用的是教程的标准配置。代理/后端是 RabbitMQ

标签: celery


【解决方案1】:

它使用AsyncResult 工作。 (见answer

所以先创建任务:

from cel.tasks import add

res = add.delay(3,4)
print(res.status) # 'SUCCESS'
print(res.id) # '432890aa-4f02-437d-aaca-1999b70efe8d'

然后启动另一个python shell:

from celery.result import AsyncResult
from cel.tasks import app

res = AsyncResult('432890aa-4f02-437d-aaca-1999b70efe8d',app=app)

print(res.state) # 'SUCCESS'
print(res.get()) # 7

【讨论】:

  • 我比 ItayB 参考中的答案更喜欢这个答案。感谢您添加参考。
  • 我只是在玩这个例子,并注意到在任务清除队列后我的状态从“SUCCESS”变为“PENDING”。参考docs.celeryproject.org/en/latest/userguide/… 的状态,以实现您的任务可能已完成,现在 task_id 已过期产生未知状态。
  • @zerocog 将不存在的id 值传递给AsyncResult 时也会发生同样的情况,即app.AsyncResult("this-is-no-id").statusPENDING,我觉得这有点烦人。例外会更有帮助。 ready()failed() 都返回 False。
  • 根据我的经验,我必须将任务放在 AsyncResult 之前。像这样:my_task.AsyncResult('taskid...') 没有其他东西对我有用。
【解决方案2】:

这是由于 RabbitMQ not actually storing the results。如果您以后需要获取结果的能力,请使用 redis 或 SQL 作为结果后端。

【讨论】:

  • 感谢您的链接。你说的似乎是这样,但是,我设法做到了(见我的回答)。这让我想到了,因为根据文档所说的(你链接的)它不应该工作。
猜你喜欢
  • 1970-01-01
  • 2019-07-20
  • 2018-11-16
  • 2023-03-07
  • 2015-05-16
  • 2022-11-25
  • 2021-02-25
  • 2012-08-27
  • 2023-02-23
相关资源
最近更新 更多