第一步安装
pip install celery==4.4
第二步 配置环境
# ############################# celery 配置连接redis ############################# #添加密码的 CELERY_BROKER_URL = 'redis://:foobared@127.0.0.1:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_BACKEND = 'redis://:foobared@127.0.0.1:6379/0' CELERY_TASK_SERIALIZER = 'json'
第三步 【项目/项目/celery.py】在项目同名目录创建 celery.py
#!/usr/bin/env python # -*- coding:utf-8 -*- # 拒绝隐式引入,因为celery.py的名字和celery的包名冲突,需要使用这条语句让程序正确运行 from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'auction.settings') app =Celery('auction') # 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中读取 tasks.py 文件 app.autodiscover_tasks()
第四步【项目/app名称/tasks.py】
from celery import shared_task @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y
第五步
from .celery import app as celery_app __all__ = ('celery_app',)
第六步 启动worker
进入项目目录 celery worker -A s -l info -P eventle
第七步 编写视图函数,调用celery去创建任务
from django.shortcuts import HttpResponse from api.tasks import x1 def create_task(request): print('请求来了') result = x1.delay(2,2) print('执行完毕') return HttpResponse(result.id) def get_result(request): nid = request.GET.get('nid') from celery.result import AsyncResult # from demos.celery import app from demos import celery_app result_object = AsyncResult(id=nid, app=celery_app) # print(result_object.status) data = result_object.get() return HttpResponse(data)
第八步 启动django程序
http://127.0.0.1:8000/api/get/task/?nid=68d4c97e-92e5-42e4-a04d-c1a8f35fb4a http://127.0.0.1:8000/api/create/task/
注意事项:
本地时间和URF实际转换:
Python3 : # 本地时间转换成utc时间 utc_ctime = datetime.datetime.utcfromtimestamp(ctime.timestamp()) target_time = utc_ctime + datetime.timedelta(seconds=10) result = x1.apply_async(args=[11, 3], eta=target_time) python2 : # “”“本地时间转UTC时间(-8:00)”“” time_struct = time.mktime(ctime.timetuple()) utc_st = datetime.datetime.utcfromtimestamp(time_struct) # utc_ctime = datetime.datetime.utcfromtimestamp(ctime.timestamp()) target_time = utc_st + datetime.timedelta(seconds=30)