[Django]-Make celery wait for task to finish

10👍

First, you’re using apply_async() wrong. The function accepts your task’s arguments packed as a tuple (args) and dictionary (kwargs) as seen here. This is because you can specify additional parameters that define how the task should run. On the other hand, delay() only accepts your task’s args and kwargs. delay() is sufficient in most cases.

You can either do this:

 example_taks.apply_async(kwargs={"user_pk":user.pk})

Or this:

example_tasks.delay(user_pk=user.pk)

You can also use positional arguments but I would recommend using kwargs when possible.

Second, waiting for an async task as soon as submitting it defeats the purpose of Celery. To wait for a task to finish you need to call get() on the result:

result = example_tasks.apply_async(kwargs={"user_pk":user.pk})
result_output = result.get()

2👍

This is how you wait for the result.

result = example_tasks.apply_async(kwargs={"user_pk": user.pk})
# Do some other things while celery is running with the task

# Sync up with the task
result.wait(timeout=10) # seconds
if result.result == 1:
    print("Do something")

Leave a comment