📌  相关文章
📜  django celery beat 的 celery beat 命令 - Python (1)

📅  最后修改于: 2023-12-03 15:30:28.468000             🧑  作者: Mango

Django Celery Beat - Celery Beat Command in Python

Introduction

Django Celery Beat is a task scheduler that runs periodic tasks at specified intervals. It is based on Celery and can be used to schedule tasks such as sending emails, updating statistics, and more. In this article, we will introduce the Celery Beat command in Python.

Installation

To install Django Celery Beat, use the following command:

pip install django-celery-beat
Usage

To use the Celery Beat command in Python, we need to define the periodic task in our Django application. For example, let's say we want to schedule a task to send an email every day at 9 am. Here is how we would define the task:

from celery.decorators import task
from django.core.mail import send_mail
from datetime import datetime

@task
def send_daily_email():
    send_mail(
        'Daily Update',
        'This is your daily update',
        'from@example.com',
        ['to@example.com'],
        fail_silently=False,
    )

Once we have defined the task, we can add it to the Celery Beat schedule in our Django settings file. Here is an example of how to do this:

CELERY_BEAT_SCHEDULE = {
    'send_daily_email': {
        'task': 'myapp.tasks.send_daily_email',
        'schedule': crontab(hour=9, minute=0),
    },
}

In this example, we have defined a task called "send_daily_email" and scheduled it to run every day at 9 am using the crontab schedule.

To start the Celery worker and beat processes, use the following command:

celery -A myapp worker -l info -B

This will start the Celery worker and beat processes, which will run the scheduled tasks at the appropriate intervals.

Conclusion

Django Celery Beat is a powerful tool for scheduling periodic tasks in a Django application. It provides a simple and flexible way to define and schedule tasks, and is easy to use with Celery. By using the Celery Beat command in Python, you can easily integrate periodic tasks into your Django application and keep your users updated with the latest information.