Junior — Middle
How to initiate the execution of an asynchronous task using Celery?
sobes.tech AI
Answer from AI
To initiate the execution of an asynchronous task using Celery in Python, you need to:
- Define the task using the
@app.taskdecorator. - Call the task using the
.delay()method or.apply_async().
Example:
from celery import Celery
app = Celery('tasks', broker='pyamqp://guest@localhost//')
@app.task
def add(x, y):
return x + y
# Initiate asynchronous execution
result = add.delay(4, 6)
# You can get the result later
print(result.get(timeout=10))
The delay() method sends the task to the queue and immediately returns an AsyncResult object, which can be used to track the status and retrieve the result.