首先需要安装必备的包
pip install celery django-celery-beat
在app中注册
INSTALLED_APPS = [
# ...
'django_celery_beat',
]
创建celery.py并配置
# project/celery.py
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
app = Celery('project')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
迁移数据库
python manage.py makemigrations
python manage.py migrate django_celery_beat
配置celery_beat
# 在celery相关配置中添加
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
启动 worker 和 beat
celery -A project worker -l info -P eventlet
celery -A project beat -l info