Sobes.tech
Junior — Middle

Can you give an example of how Celery is used to perform asynchronous tasks?

sobes.tech AI

Answer from AI

Celery is a Python library that allows you to perform tasks asynchronously, in the background, using a message broker (such as RabbitMQ or Redis).

Example of using Celery:

from celery import Celery

app = Celery('tasks', broker='redis://localhost:6379/0')

@app.task
def add(x, y):
    return x + y

# In another part of the application
result = add.delay(4, 6)  # Runs the task asynchronously
print(result.id)  # Task ID
print(result.get(timeout=10))  # Get the result (blocking call)

Here, the add function becomes a Celery task. Calling add.delay() puts the task in the queue, and it will be executed by a worker in the background, without blocking the main application thread.