django中使用celery
1.目录结构
在settings配置中添加
INSTALLED_APPS = [ 'celery',]
下载的包
pip install celery
pip install django-celery
pip install redis==2.10.6
2.celery.py
import os import django
#导入django的环境这样就可以在celery中运行orm os.environ.setdefault("DJANGO_SETTINGS_MODULE", "repi.settings") django.setup() from celery import Celery
#本地的redis链接 broker='redis://127.0.0.1:6379/3' backend='redis://127.0.0.1:6379/4' app=Celery('celery_stask',broker=broker,backend=backend,include=['celery_stask.stask'])#celery_stask.stask任务文件 # app=Celery('celery_stask',include=['celery_stask.stask']) # 时区 app.conf.timezone = 'Asia/Shanghai' # 是否使用UTC app.conf.enable_utc = False from datetime import timedelta app.conf.beat_schedule={ 'add-every-5-seconds':{ 'task':'celery_stask.stask.Timing_insert', 'schedule':timedelta(seconds=10), 'args':()#如果调用的对象又形参这里就要加形参 } }
2.stask
from .celery import app import time @app.task def Timing_insert(): #代码
return True
调用方式
Timing_insert.delay()
在 celery_stask目录下输入这两条命令
celery beat -A celery_stask -l info
celery worker -A celery_stask.stask -l info