包的版本
- pip3 install celery
- pip3 install django-celery
- pip3 install redis==2.10.6
启动命令
# linux / mac下
celery -A 项目名 worker -l info --beat
# windows下
celery -A 项目名 worker -l info -P eventle
主应用目录下
setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'djcelery', # 添加celery应用
]
# celery config
# 消息中间件(使用redis),消息代理,用于发布者传递消息给消费者
BROKER_URL = 'redis://127.0.0.1:6379/1'
# 消息结果返回中间件(使用redis),用于存储任务执行结果
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/2'
# 允许的内容类型,
CELERY_ACCEPT_CONTENT = ['json']
# 任务的序列化方式
CELERY_TASK_SERIALIZER = 'json'
# 任务结果的序列化方式
CELERY_RESULT_SERIALIZER = 'json'
__init__.py
from __future__ import absolute_import
from .celery import app as celery_app
celery.py
from __future__ import absolute_import, unicode_literals
import os
from django.conf import settings
from celery import Celery
# 设置 Django 的配置文件
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'roamsaverb2b.settings')
# 创建 celery 实例
app = Celery('test1')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
# 搜索所有 app 中的 tasks
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
子应用目录下
tasks.py
# -*- coding:utf-8 -*-
from __future__ import absolute_import
import time
from roamsaverb2b.celery import app
@app.task
def add(x, y):
time.sleep(30)
print("running...", x, y)
return x + y
# 状态有这几种情况
CELERY_STATUS = {
'PENDING': '执行中',
'STARTED': '任务开始',
'SUCCESS': '成功',
'FAILURE': '失败',
'RETRY': '重试',
'REVOKED': '任务取消',
}
if __name__ == '__main__':
status = app.AsyncResult('任务id').status
result = app.AsyncResult('任务id').result
print(status)
print(result)
views.py
class IndexPage(View):
def get(self, request):
res = add.delay(1,2)
print(res.id) # 打印任务id,可记录到日志,方便管理
return render(request, 'index.html')
注意事项
- redis版本不能过高,过高会导致celery启动报错
- windows下使用celery需安装pip install eventlet
- 还有启动错误情况是因为redis需要修改配置文件
config set stop-writes-on-bgsave-error no