Welcome to our tutorial on Django Celery Beat! Today, we'll learn how to set up and use Celery Beat for real-time task scheduling in your Django projects.
Django Celery Beat is a part of Celery, a powerful task queue system for Python. Beat is a daemon/service that ensures your tasks are executed at the scheduled time.
First, let's ensure you have Celery and Redis installed. If not, check out our Django Celery tutorial.
pip install celery[beat]Now, let's set up Celery Beat in your Django project.
celery.py file:from celery import Celery
from celery.schedules import crontab
app = Celery('my_project')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
app.conf.beat_schedule = {
'run-every-minutes': {
'task': 'my_app.tasks.sample_task',
'schedule': crontab(minute='*/1'),
},
}π Note: Replace my_app with the name of your app and sample_task with the name of the task you want to schedule.
In a separate terminal, run:
celery beat -A my_project.celeryNow, Celery Beat is running and scheduling your tasks!
Let's create a simple task to be executed every minute.
my_app/tasks.py:from celery import shared_task
@shared_task
def sample_task():
print('Sample task executed!')Now, try checking the logs to see if your task is being executed every minute:
tail -f /var/log/celerybeat-schedule.logWhat should you run in a separate terminal to start Celery Beat?
Congratulations! You've now set up Django Celery Beat and learned how to schedule tasks in your Django projects. This opens up a world of possibilities for automating repetitive tasks, running complex workflows, and even creating real-time web applications!
Stay tuned for more tutorials on Django Celery and other exciting topics. Happy coding! π