版本选择:
celery4不再支持windows,所以在Windows环境下使用请选择celery==3.1.18
参考:https://github.com/celery/celery/issues/3551
参考文档:
http://docs.celeryproject.org/en/3.1/
一. 简介
celery是一个基于python开发的简单、灵活且可靠的分布式任务队列框架,支持使用任务队列的方式在分布式的机器/进程/线程上执行任务调度。采用典型的生产者-消费者模型,主要由三部分组成:
1. 消息队列broker:broker实际上就是一个MQ队列服务,可以使用redis、rabbitmq等作为broker
2. 处理任务的消费者workers:broker通知worker队列中有任务,worker去队列中取出任务执行,每一个worker就是一个进程
3. 存储结果的backend:执行结果存储在backend,默认也会存储在broker使用的MQ队列服务中,也可以单独配置用何种服务做backend
---------------------
二. 配置到Django
典型的django项目框架:
- proj/
- proj/__init__.py
- proj/settings.py
- proj/urls.py
- manage.py
1. 创建/proj/proj/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', 'dbmon.settings')
from django.conf import settings # noqa
app = Celery('dbmon')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
# 此处celery将会找到在每一个app下的tasks.py文件并将之将在
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
2. 在/proj/proj/__init__.py中导入这个app,确保django每次启动都能加载到从而才能使用@shared_task装饰器
from __future__ import absolute_import
# 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 # noqa
3. 在每个app下创建task文件
就像这样
- app1/
- app1/tasks.py
- app1/models.py
- app2/
- app2/tasks.py
- app2/models.py
tasks.py
#! /usr/bin/python
# encoding:utf-8
# Create your tasks here
from __future__ import absolute_import,unicode_literals
from celery import shared_task
import frame.oracle_do as oracle
import frame.mysql_do as mysql
@shared_task
def add(x,y):
return x+y
@shared_task
def