Django Celery Beat: Real-time Task Scheduling in Django Projects 🎯

beginner
14 min

Django Celery Beat: Real-time Task Scheduling in Django Projects 🎯

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.

What is Django Celery Beat? πŸ“

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.

Why use Django Celery Beat? πŸ’‘

  • Scheduling tasks: Run tasks at specific intervals or dates
  • Simplifying complex tasks: Break down complex tasks into smaller, manageable ones
  • Scalability: Easily handle high volumes of work with minimal overhead

Setting Up Django Celery Beat 🎯

First, let's ensure you have Celery and Redis installed. If not, check out our Django Celery tutorial.

Installing Django Celery Beat πŸ“

bash
pip install celery[beat]

Now, let's set up Celery Beat in your Django project.

  • Add the following to your celery.py file:
python
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.

Running Celery Beat πŸ’‘

In a separate terminal, run:

bash
celery beat -A my_project.celery

Now, Celery Beat is running and scheduling your tasks!

Creating a Scheduled Task 🎯

Let's create a simple task to be executed every minute.

  • In my_app/tasks.py:
python
from celery import shared_task @shared_task def sample_task(): print('Sample task executed!')

Testing Your Scheduled Task πŸ’‘

Now, try checking the logs to see if your task is being executed every minute:

bash
tail -f /var/log/celerybeat-schedule.log
Quick Quiz
Question 1 of 1

What should you run in a separate terminal to start Celery Beat?

Conclusion 🎯

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! πŸŽ‰