Celery wait for a task from another request

Viewed 277

Let's say there is a long task that takes 1 minute. When a user makes a request /get-info and waiting for the response it should return a result. I'm using delay(), wait() and everything works. Now I want if another 5 users make same request /get-info I want them 'connect' to the same task and get result once the task is finished. I'm trying to save task id in redis. But so far I'm having 2 problems.

  1. If I use AsyncResult() and wait() the second request hangs.

  2. If I use AsyncResult() and state, the first request hangs. How can I implement that?

@main.route('/get-info', methods=['POST'])
def get_info():
    if redis.exists('getInfoTaskId'):
        taks_id = redis.get('getInfoTaskId')
        task = add_together.AsyncResult(taks_id)
        result = task.wait()
        # result = task.state - if uncomment and comment the line above the first req hangs
    else:
        task = add_together.delay(23, 42)
        redis.set('getInfoTaskId', task.id, ex=600)
        result = task.wait()
        redis.delete('getInfoTaskId')

    return f"task result is {result}"
0 Answers
Related