0
0
Djangoframework~5 mins

Periodic tasks with Celery Beat in Django

Choose your learning style9 modes available
Introduction

Periodic tasks let your app do things automatically at set times, like sending reminders or cleaning up data. Celery Beat helps schedule these tasks easily.

Send daily email summaries to users every morning.
Clean up expired sessions from the database every hour.
Generate reports automatically at midnight.
Check for updates from an external service every 10 minutes.
Syntax
Django
from celery import Celery
from celery.schedules import crontab

app = Celery('myapp')

app.conf.beat_schedule = {
    'task-name': {
        'task': 'myapp.tasks.my_task',
        'schedule': crontab(minute=0, hour=7),  # every day at 7:00 AM
        'args': (),
    },
}

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

crontab lets you set schedules like a clock (e.g., every day at 7 AM).

Define your periodic tasks inside beat_schedule with a unique name.

Examples
This runs quick_task every 10 seconds using a simple float for seconds.
Django
app.conf.beat_schedule = {
    'run-every-10-seconds': {
        'task': 'myapp.tasks.quick_task',
        'schedule': 10.0,  # every 10 seconds
        'args': (),
    },
}
This runs send_report once daily at midnight using crontab.
Django
app.conf.beat_schedule = {
    'daily-report': {
        'task': 'myapp.tasks.send_report',
        'schedule': crontab(hour=0, minute=0),  # every day at midnight
        'args': (),
    },
}
This runs weekly_cleanup every Monday at 9:30 AM.
Django
app.conf.beat_schedule = {
    'every-monday-morning': {
        'task': 'myapp.tasks.weekly_cleanup',
        'schedule': crontab(hour=9, minute=30, day_of_week='mon'),
        'args': (),
    },
}
Sample Program

This example sets up a task called say_hello that prints a message every minute. Celery Beat will trigger it automatically.

Django
from celery import Celery
from celery.schedules import crontab

app = Celery('myapp')

app.conf.broker_url = 'redis://localhost:6379/0'
app.conf.beat_schedule = {
    'say-hello-every-minute': {
        'task': 'myapp.tasks.say_hello',
        'schedule': crontab(minute='*'),  # every minute
        'args': (),
    },
}

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

Make sure your Celery worker and Celery Beat scheduler are running to execute periodic tasks.

Use Redis or RabbitMQ as the message broker for Celery to work smoothly.

Test your tasks manually before scheduling to avoid silent failures.

Summary

Celery Beat schedules tasks to run automatically at set times.

Use beat_schedule with crontab or seconds to set timing.

Run both Celery worker and Beat to see periodic tasks in action.