首先需要确保安装依赖
pip install celery redis eventlet
在创建的app文件内添加tasks.py
# app01/tasks.py
from celery import shared_task
@shared_task
def simple_task():
print('Task executed successfully')
在项目目录下(与settings.py文件同级)添加celery.py
# Projects/project_api/celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# 设置默认的 Django settings 模块
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_api.settings')
app = Celery('project_api')
# 使用 Django 的 settings 文件配置 Celery
app.config_from_object('django.conf:settings', namespace='CELERY')
# 手动导入任务模块
app.autodiscover_tasks(lambda: ['app01.tasks'])
配置settings.py
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'
from .celerybeat_schedule import CELERY_BEAT_SCHEDULE
配置celerybeat_schedule.py(以每隔10秒执行一次为例)
# Projects/project_api/celerybeat_schedule.py
from celery.schedules import crontab
CELERY_BEAT_SCHEDULE = {
'execute-simple-task-every-10-seconds': {
'task': 'app01.tasks.simple_task',
'schedule': 10.0, # 每隔10秒钟执行一次
},
}
启动worker和beat
# 开启两个命令框,分别执行
celery -A Reports worker -l info -P eventlet
celery -A Reports beat -l info