0
0
Flaskframework~5 mins

Defining Celery tasks in Flask

Choose your learning style9 modes available
Introduction

Celery tasks let your Flask app do work in the background. This helps keep your app fast and responsive.

Sending emails after a user signs up without making them wait
Processing uploaded files without blocking the user
Running scheduled jobs like cleaning up old data
Handling long calculations without freezing the app
Syntax
Flask
from celery import Celery

celery_app = Celery('myapp', broker='redis://localhost:6379/0')

@celery_app.task
def my_task(arg1, arg2):
    # task code here
    return arg1 + arg2

Use @celery_app.task to mark a function as a background task.

The broker is where Celery gets tasks from; Redis is a common choice.

Examples
A simple task that adds two numbers.
Flask
from celery import Celery

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

@celery_app.task
def add(x, y):
    return x + y
A task that simulates sending an email.
Flask
from celery import Celery

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

@celery_app.task
def send_email(to_address):
    print(f"Sending email to {to_address}")
A task that retries itself on failure after 10 seconds.
Flask
from celery import Celery

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

@celery_app.task(bind=True)
def retry_task(self):
    try:
        # risky code
        pass
    except Exception as e:
        self.retry(exc=e, countdown=10)
Sample Program

This program defines a Celery task to multiply two numbers. It sends the task to the queue and prints the task ID.

Flask
from celery import Celery

celery_app = Celery('flask_app', broker='redis://localhost:6379/0')

@celery_app.task
def multiply(x, y):
    return x * y

if __name__ == '__main__':
    result = multiply.delay(4, 5)
    print(f"Task sent. Task ID: {result.id}")
OutputSuccess
Important Notes

Remember to run a Celery worker separately to process tasks.

Use delay() to call tasks asynchronously.

Task IDs help track the status of background jobs.

Summary

Use @celery_app.task to define background tasks in Flask.

Tasks run outside the main app to keep it fast.

Call tasks with delay() to run them asynchronously.