首先安装redis,这里将不一一结束redis的安装。html
pip install celery
1、在django项目的settings中添加:redis
# Celery settings CELERY_BROKER_URL = 'redis://localhost' CELERY_RESULT_BACKEND = 'redis://localhost' CELERY_IMPORTS = ("这里导入的是须要执行方法的文件", ) # 若是不加这一行的话,会显示任务为注册,查了很久也没查出缘由,因此加上这条配置,导入方法 #: Only add pickle to this list if your broker is secured #: from unwanted access (see userguide/security.html) CELERY_TASK_TRACK_STARTED = True CELERY_TASK_SOFT_TIME_LIMIT = 240 CELERY_TASK_TIME_LIMIT = 300 CELERY_WORKER_SEND_TASK_EVENTS = True CELERY_TASK_SEND_SENT_EVENT = True CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json'
2、在项目的app下建立celery.pydjango
from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', '项目名.settings') app = Celery('项目名') # this ‘demo’ is your project name !!! # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks()
3、而后写须要执行的方法:json
import time from celery import Celery celery_app = Celery('该文件路径', backend='redis://localhost', broker='redis://localhost') # this is celery settings # this is a function about need many time @celery_app.task def add(a, b): time.sleep(5) return a + b
4、最后执行命令app
celery -A 项目名 worker --loglevel=info --pool=solo