首先需要安裝必備的包
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