安装
celery
pip install celery
pip install flower
pip install redis
redis安装-百度有教
例子
文档目录
setting.py
# CELERY STUFF
BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Shanghai'
init.py
from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app #加载时候加进去
celery.py
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api_sys.settings')
app = Celery('api_sys')
# 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.autodiscover_tasks(lambda: settings.INSTALLED_APPS
task.py
import logging
from api_sys.celery import app
from celery import shared_task
import time
@app.task
def dosomething(a,b):
try:
s = a + b
time.sleep(5)
logging.info("%d + %d = %d" % (a,b, s))
return s
except:
logging.warning('has error')
return 0
@shared_task
def mul(a,b):
try:
s = a * b
time.sleep(5)
logging.info("%d * %d = %d" % (a,b, s))
return s
except:
logging.warning('has error')
retur
views.py
def test_task(request):
"""
测试例子,调用时候用delay异步启动任务
"""
a = request.GET.get('a', '0')
b = request.GET.get('b', '0')
try:
a = int(a)
b = int(b)
except:
a = 0
b = 0
res1 = dosomething.delay(a,b)
res2 = mul.delay(a, b)
return JsonResponse({'a':a, 'b':b}
启动服务
# 启动redis
redis-5.1.4/src/redis-server
# 先到项目文件主目录
# 启动Django
python manage.py runserver
# 启动celery
celery -A api_sys worker -c 4 --loglevel=info
# 启动Flower监控
celery -A api_sys flo