56

I am trying to retreive the result of a task which has completed. This works

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

But I want to run this from another application. So I rerun python shell and try:

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

How can I retrieve the result?

Demetris
  • 2,981
  • 2
  • 25
  • 33

2 Answers2

99

It works using AsyncResult. (see this answer)

So first create the task:

from cel.tasks import add

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

Then start another 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
Phani Rithvij
  • 4,030
  • 3
  • 25
  • 60
Demetris
  • 2,981
  • 2
  • 25
  • 33
  • 2
    Just adding a reference: http://stackoverflow.com/questions/5544611/retrieve-a-task-result-object-given-a-task-id-in-celery – ItayB Jan 17 '17 at 14:42
  • I like this answer better than the one in the reference by ItayB. Thanks for adding the reference. – zerocog Jul 14 '17 at 00:15
  • 2
    I was just toying with the example, and noticed that my state changed from 'SUCCESS' to 'PENDING' after the task cleared the queue. Reference state at http://docs.celeryproject.org/en/latest/userguide/tasks.html#std:state-PENDING to realize your task may have completed, and now the task_id has expired yielding the unknown state. – zerocog Jul 14 '17 at 01:28
  • 4
    @zerocog The same happens when passing non-existing `id` values to `AsyncResult`, i.e. `app.AsyncResult("this-is-no-id").status` is `PENDING` which I found somewhat irritating. An exception would have been more helpful. Both `ready()` and `failed()` return False. – Jens Sep 27 '17 at 06:53
  • 2
    In my experience I had to put the task before AsyncResult. Like this: `my_task.AsyncResult('taskid...')` Nothing else worked for me. – Jason Oct 07 '18 at 13:12
  • For me I needed to add "celery-task-meta-" in front of task id when I search in redis backend. – tolga Dec 17 '22 at 19:35
11

This is due to RabbitMQ not actually storing the results. If you need the ability to get the results later on, use redis or SQL as the result backend.

tuomur
  • 6,888
  • 34
  • 37
  • Thank you for the link. What you say seems to be the case, however, I managed to do it (see my answer). This makes me think though because according to what the documentation says (what you linked) it shouldn't work. – Demetris Jun 10 '15 at 15:03