首先安装必要的包:
pip install celery
pip install redis
project层:
setting.py
BROKER_URL = 'redis://127.0.0.1:6379/1' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/3' BROKER_TRANSPORT = 'redis'
celery.py
from __future__ import absolute_import # 解决命名问题 import os import django from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', '项目名.settings') # 设置配置文件 django.setup() app = Celery('项目名') app.config_from_object('django.conf:settings') # 制定celery配置文件 app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # 任务 # app.conf.result_backend = 'redis://localhost:6379/2'
__init__.py
from __future__ import absolute_import, unicode_literals # 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 __all__ = ('celery_app',)
现在来到app:
tasks.py
from djcelery.celery import app @app.task def send(): import time print('begin') time.sleep(5) print('end') return 25
views.py
from django.shortcuts import HttpResponse from .tasks import send def test(request): send.delay() return HttpResponse('nihao')
开启任务:
celery -A djcelery worker -l debug