celery在Django中的使用

celery在Django中的使用

version
django==1.11.20
celery==3.1.26
django-celery==3.3.1
redis==2.10.6
window下
1.配置安装redis,手动命令启动redis,保证redis正常运行(嫌麻烦,配置成windows服务,搜索运行,输入services.msc,找到Redis启动即可)
2.在django项目settings同级的目录下创建celery.py文件
3.修改django项目settings同级的目录下__init__.py文件
4.安装django-celery(使用python manage.py 启动celery)
5.配置djcelery
INSTALLED_APPS = [
    ...
    'djcelery',
    ...
    ]
在settings里面写入celery一些配置即可
6.启动celery:python manage.py celery worker -l INFO

使用的项目目录

proj

init.py

setting.py

celery.py

urls.py

wsgi.py

myapp

init.py

tasks.py

views.py

model.py

celery.py

from __future__ import absolute_import

import os

from celery import Celery, platforms

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'LIMSv2.settings')  # 修改成项目名

from django.conf import settings  # noqa

# celery相关
BROKER_URL = "redis://127.0.0.1:6379/0"
app = Celery('LIMSv2', backend=BROKER_URL, broker=BROKER_URL)  # 创建app,修改成项目名
platforms.C_FORCE_ROOT = True

# 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)#自动搜索INSTALLED_APPS下所有的tasks.py文件

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',)

tasks.py

from __future__ import absolute_import

import time

from celery.task import task


@task
def test_celery(x, y):
    time.sleep(3)
    return "抢购成功。。"

posted @ 2020-04-16 09:44  烧刘病  阅读(217)  评论(2编辑  收藏  举报
回到页首