Get ready for your next interview with our comprehensive question library
Celery is an asynchronous task queue/job queue system based on distributed message passing. It's used to execute tasks asynchronously (in the background) and schedule periodic tasks. Key use cases include:
Celery consists of several key components:
Celery supports multiple message brokers:
RabbitMQ is recommended for production due to its reliability and full feature support.
Both methods are used to execute tasks asynchronously:
delay()
: Shortcut method, simpler syntax for basic task executionapply_async()
: More powerful, allows passing execution options# Using delay
task.delay(arg1, arg2)
# Using apply_async with options
task.apply_async(args=[arg1, arg2],
countdown=10,
retry=True)
Celery serializes task messages and results to transmit them over the network. Supported serializers include:
Configuration example:
app.conf.task_serializer = 'json'
app.conf.result_serializer = 'json'
app.conf.accept_content = ['json']
Tasks are defined using the @app.task
decorator:
from celery import Celery
app = Celery('tasks', broker='redis://localhost')
@app.task
def add(x, y):
return x + y
self
as the first argument, providing access to task metadata# Bound task
@app.task(bind=True)
def debug_task(self):
print(f'Request: {self.request!r}')
Upgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumUpgrade to Premium to see the answer
Upgrade to PremiumAccess all premium content - interview questions, and other learning resources
We regularly update our features and content, to ensure you get the most relevant and updated premium content.
1000 monthly credits
Cancel anytime