0
0
Flaskframework~5 mins

Periodic tasks with Celery Beat in Flask

Choose your learning style9 modes available
Introduction

Periodic tasks let your app do things automatically at set times. Celery Beat helps schedule these tasks easily.

Send daily reminder emails to users.
Clean up old files every night.
Update data from an external source every hour.
Generate reports every Monday morning.
Syntax
Flask
from celery import Celery
from celery.schedules import crontab

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

app.conf.beat_schedule = {
    'task-name': {
        'task': 'module.task_function',
        'schedule': crontab(minute=0, hour=0),  # runs daily at midnight
    },
}

@app.task
def task_function():
    # task code here
    pass

Use crontab to set the schedule in a human-friendly way.

Define tasks with @app.task decorator.

Examples
This runs the send_email task every minute.
Flask
app.conf.beat_schedule = {
    'send-email-every-minute': {
        'task': 'tasks.send_email',
        'schedule': crontab(),  # runs every minute
    },
}
This runs generate_report every Monday morning at 9 AM.
Flask
app.conf.beat_schedule = {
    'weekly-report': {
        'task': 'tasks.generate_report',
        'schedule': crontab(minute=0, hour=9, day_of_week='mon'),  # every Monday at 9:00 AM
    },
}
Sample Program

This example sets up a task that prints a message every 10 seconds automatically.

Flask
from celery import Celery
from celery.schedules import crontab

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

app.conf.beat_schedule = {
    'print-hello-every-10-seconds': {
        'task': 'myapp.print_hello',
        'schedule': 10.0,  # every 10 seconds
    },
}

@app.task
def print_hello():
    print('Hello from Celery Beat!')
OutputSuccess
Important Notes

Make sure Redis or your broker is running before starting Celery and Beat.

Run celery -A myapp beat to start the scheduler.

Run celery -A myapp worker to start the worker that executes tasks.

Summary

Celery Beat schedules tasks to run automatically at set times.

Use crontab or seconds for flexible scheduling.

Tasks must be defined with @app.task and registered in beat_schedule.