dab0bby
dab0bby

Reputation: 2991

How to use result callback for celery AsyncTask

I have the following situatuion.

My client sends following task to the worker:

# client
task = my_task.apply_async((some_params), queue='my_queue')
# task.get()  # This blocks

My worker executes the task properly and returns the result.

So retrieving the result with task.get() works but it blocks. Now what I'd like to have is a callback that is called when a result (success or failure) is available.

There is a on_success function of the Task class. But that is used in the worker. Similiar Question

Any ideas or solutions?

Upvotes: 5

Views: 3897

Answers (1)

2ps
2ps

Reputation: 15916

You can have callbacks with a task, but it's not the caller or client that can be notified or called back (because celery is out of process), it will be another celery task that has to be used as the callback. If you would like to use a callback, you can use celery's link or canvassing functionality.

For a simple callback that uses the result of the initiating task you can do the following:


@app.task
def add(m, n):
    return m + n

@app.task
def callback(result):
    print(f'My result was {result}')

def client_caller():
    add.apply_async(args=(2, 2), link=callback.s())


Upvotes: 6

Related Questions