Retrieve result from 'task_id' in Celery from unknown task

前端 未结 2 865
深忆病人
深忆病人 2021-01-01 23:04

How do I pull the result of a task if I do not know previously which task was performed? Here\'s the setup: Given the following source(\'tasks.py\'):

from ce         


        
相关标签:
2条回答
  • 2021-01-01 23:53

    Ok - so I've been looking for a solution for a long time, and now that I've finally formally posted this and looked over the documentation I found this gem:

    class celery.result.AsyncResult(id, backend=None, task_name=None, app=None, parent=None)

    Query task state.

    Parameters:

    id – see id.

    backend – see backend.

    exception TimeoutError

    Error raised for timeouts.

    AsyncResult.app = None

    So instead of providing the backend parameter I provided the "app" argument instead like so:

    from celery.result import AsyncResult
    from task import app
    
    # Assuming add.delay(10,10) was called in another process
    # and that I'm using a 'task_id' I retrieved from that process
    
    result = AsyncResult(id='copied_task_id', app=app)
    result.state # 'SUCCESSFUL'
    result.get() # 20
    

    This is probably obvious to many. It wasn't to me. For now all I can say is that this solution "just works", but I'd feel more comfortable if I knew it was the sanctioned way to do it. If you know of a section in the documentation that makes this more clear please post it in the comments or as an answer and I'll select it as the answer if I can.

    0 讨论(0)
  • 2021-01-01 23:59

    In case it helps anyone, it turns out that backend parameter doesn't expect a string, but a Backend object: How do I override the backend for celery tasks

    What worked for me was:

    from celery.backends.rpc import RPCBackend
    from myapp.workers.main import app as worker
    
    @worker.task(backend=RPCBackend(app=worker))
    def status_check():
        return "OK"
    
    0 讨论(0)
提交回复
热议问题