推荐版本:
Django==2.2.6
django-celery==3.3.1
Django=redis==4.11.0
redis==2.10.6
celery==3.1.26post2
settings.py:
import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/2'
INSTALLED_APPS = [
"djcelery",
]
创建celery需要的数据表
python manage.py migrate
如果失败的话可以试试
#python manage.py syncdb
然后在Django的APP下面在创建tasks.py
tasks.py:
from celery import task
from celery import task
import time
@task
def add(x, y):
result = x + y
time.sleep(5) # 可有可无,睡眠五秒
# print(f'{add.__name__}结果为:', result)
return result
Views.py:
from rest_framework.views import APIView
from rest_framework.response import Response
from app01.tasks import add
class TestCeleryView(APIView):
def get(self, request):
add.delay(5, 10) # delay是注册为celery异步任务的关键点
return Response({"code": 200})
启动celery:
python manage.py celery worker --loglevel=infov
如果报错不让超级管理员来启动,在settings.py加入以下配置
from celery import Celery, platforms
platforms.C_FORCE_ROOT = True