Celery


Background

Celery is a distributed task queue that allows you to run tasks asynchronously in a distributed manner. It is often used to improve the performance and scalability of applications by offloading long-running or resource-intensive tasks to a separate worker process.

1. Simple Task Scheduling

from celery import Celery

app = Celery('tasks')

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

add.delay(10, 20)

This schedules the add task to be executed asynchronously. The delay method returns a task object that you can use to check its status or retrieve its result.

2. Periodic Tasks

from celery.schedules import crontab

@app.task
def send_email():
    # Send an email

app.conf.beat_schedule = {
    'send-email': {
        'task': 'tasks.send_email',
        'schedule': crontab(hour=10, minute=0),
    }
}

This creates a periodic task that will run the send_email task every day at 10:00 AM.

3. Chaining Tasks

This chains the task1 and task2 tasks together. The task2 task will be executed with the result of the task1 task as input.

4. Retrying Tasks

This configures the task to be retried automatically if it fails. The retry_backoff and retry_jitter options control the delay between retries and the variation in retry delay, respectively.

5. Limiting Concurrency

This limits the number of concurrent executions of the task to 5 and terminates the task if it takes longer than 5 minutes to complete.

6. Task Groups

This creates a group of tasks that are executed in parallel. The result object can be used to retrieve the results of all the tasks in the group.

7. Task Chords

This creates a chord that depends on the completion of the add_tasks tasks. The result object can be used to retrieve the final result of the chord, which is the sum of the results of the add_tasks.

8. Queues and Routing

This creates two different queues, high-priority and low-priority. The tasks are routed to the appropriate queue based on their queue configuration.

9. Custom Task Classes

This creates a custom task class that inherits from the Celery.Task class. You can override the run method to customize the behavior of the task.

10. Custom Serializer

This creates a custom serializer that serializes and deserializes task data. You can use this to customize the way task data is stored and transmitted.