When creating a web application, there are often times when you need to perform long-running tasks. For example:

  • When a user signs up, you need to send a verification email.
  • You have to run data cleanup tasks automatically at midnight every day.
  • When a user schedules a specific task, it must be executed at the specified time.

Django works by responding immediately when a request comes in, so there is a need for a way to handle long-running tasks asynchronously. This is where Celery comes into play! 🚀

Celery is a powerful tool that helps you execute asynchronous tasks in Django, and Celery-Beat helps you execute specific tasks at scheduled times.

Django Celery-Beat task scheduling illustration

1️⃣ How to Set Up Scheduled Tasks in Django-Celery-Beat

There are two main ways to set up scheduled tasks in Celery-Beat.

✅ (1) Set Up Scheduling via GUI in Django Admin

Django-Celery-Beat supports setting scheduled tasks directly through the GUI in Django Admin.

📌 Features
  • You can execute periodic tasks with simple settings without coding.
  • You can set and modify periodic tasks through the UI on the Django admin page.
  • However, since it is a static setup, it is difficult to change dynamically based on user requests.
📌 When is it Good to Use?
  • When interaction between the application and users is not necessary
  • Example) Automated data backup that runs at midnight every day
  • Example) Updating specific API data every Monday morning

✅ (2) Dynamically Create Scheduled Tasks Using Python Code

You can also create scheduled tasks directly through code in Celery-Beat.

📌 Features
  • You can dynamically create scheduled tasks based on user requests.
  • You can create, change, and delete scheduled tasks through code.
  • You can register periodic tasks directly from the view without going through the Admin.
📌 When is it Good to Use?
  • When a scheduled task is needed upon a specific user request.
  • Example) When a user places a “reserved order,” automatically register a task to cancel it after 2 hours.
  • Example) When a user sets the “email reminder” feature, schedule it to send a reminder email at the specified time.

2️⃣ [Practice] Creating Scheduled Tasks with Python Code

Step 1: Define a Celery Task

from celery import shared_task

@shared_task
def send_reminder_email(user_id):
    # Implement email sending logic here
    print(f"📧 A reminder email has been sent to user {user_id}!")

Step 2: Create a PeriodicTask Object in Django-Celery-Beat

from django_celery_beat.models import PeriodicTask, IntervalSchedule
import json

# 1️⃣ Create the execution interval (e.g., run every 10 minutes)
schedule, created = IntervalSchedule.objects.get_or_create(
    every=10,  # every 10 minutes
    period=IntervalSchedule.MINUTES
)

# 2️⃣ Create the PeriodicTask
task = PeriodicTask.objects.create(
    interval=schedule,  # execution interval
    name="Send Reminder Email",  # task name
    task="myapp.tasks.send_reminder_email",  # name of the Celery task to run
    args=json.dumps([1]),  # pass user ID (using example user ID 1)
)

🎯 Conclusion: Celery is Essential for Django Developers!

Celery is an essential tool for managing asynchronous tasks and enabling scheduled execution in Django.

In particular, using Celery-Beat allows you to set periodic tasks and manage scheduling dynamically based on specific events.

📌 To summarize:

  1. Django-Celery-Beat is a powerful tool for executing scheduled tasks.
  2. You can easily set periodic tasks using Django Admin (GUI).
  3. Creating tasks via Python code allows for dynamic management of scheduled tasks based on user requests.
  4. Django developers must learn the fundamental concepts of Celery and Celery-Beat!

🔥 Preview of the Next Episode

In this episode, we briefly introduced how to create scheduled tasks in Celery-Beat via code. However, in practice, you will utilize more various fields of the `PeriodicTask` model to manage more complex logic.

In the next episode, we will take a closer look at practical code for scheduling various tasks and what each field of the `PeriodicTask` model does.

If you want to learn more about advanced usage of Celery, stay tuned for the next installment! 🚀

Also, if you want to read more posts related to Celery on the blog,

check the 'Similar Posts' list below or search for “Celery” in the search box at the top right! 😊