原生celery,非djcelery模块,全部演示均基于Django2.0html
celery是一个基于python开发的简单、灵活且可靠的分布式任务队列框架,支持使用任务队列的方式在分布式的机器/进程/线程上执行任务调度。采用典型的生产者-消费者模型,主要由三部分组成:前端
个人异步使用场景为项目上线:前端web上有个上线按钮,点击按钮后发请求给后端,后端执行上线过程要5分钟,后端在接收到请求后把任务放入队列异步执行,同时立刻返回给前端一个任务执行中的结果。若果没有异步执行会怎么样呢?同步的状况就是执行过程当中前端一直在等后端返回结果,页面转呀转的就转超时了。python
1.安装rabbitmq,这里咱们使用rabbitmq做为broker,安装完成后默认启动了,也不须要其余任何配置git
# apt-get install rabbitmq-server 复制代码
2.安装celerygithub
# pip3 install celery 复制代码
3.celery用在django项目中,django项目目录结构(简化)以下web
website/
|-- deploy
| |-- admin.py
| |-- apps.py
| |-- __init__.py
| |-- models.py
| |-- tasks.py
| |-- tests.py
| |-- urls.py
| `-- views.py
|-- manage.py
|-- README
`-- website
|-- celery.py
|-- __init__.py
|-- settings.py
|-- urls.py
`-- wsgi.py
复制代码
4.建立website/celery.py
主文件redis
from __future__ import absolute_import, unicode_literals import os from celery import Celery, platforms # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings') app = Celery('website') # Using a string here means the worker don'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() # 容许root 用户运行celery platforms.C_FORCE_ROOT = True @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) 复制代码
5.在website/__init__.py
文件中增长以下内容,确保django启动的时候这个app可以被加载到django
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 __all__ = ['celery_app'] 复制代码
6.各应用建立tasks.py文件,这里为deploy/tasks.py
后端
from __future__ import absolute_import from celery import shared_task @shared_task def add(x, y): return x + y 复制代码
7.views.py中引用使用这个tasks异步处理bash
from deploy.tasks import add
def post(request):
result = add.delay(2, 3)
复制代码
result.ready()
来判断任务是否完成处理result.get(timeout=1)
能够从新抛出异常result.traceback
能够获取原始的回溯信息8.启动celery
# celery -A website worker -l info 复制代码
9.这样在调用post这个方法时,里边的add就能够异步处理了
定时任务的使用场景就很广泛了,好比我须要定时发送报告给老板~
1.website/celery.py
文件添加以下配置以支持定时任务crontab
from celery.schedules import crontab app.conf.update( CELERYBEAT_SCHEDULE = { 'sum-task': { 'task': 'deploy.tasks.add', 'schedule': timedelta(seconds=20), 'args': (5, 6) } 'send-report': { 'task': 'deploy.tasks.report', 'schedule': crontab(hour=4, minute=30, day_of_week=1), } } ) 复制代码
定义了两个task:
timedelta是datetime中的一个对象,须要from datetime import timedelta
引入,有以下几个参数
days
:天seconds
:秒microseconds
:微妙milliseconds
:毫秒minutes
:分hours
:小时crontab的参数有:
month_of_year
:月份day_of_month
:日期day_of_week
:周hour
:小时minute
:分钟2.deploy/tasks.py
文件添加report方法:
@shared_task def report(): return 5 复制代码
3.启动celery beat,celery启动了一个beat进程一直在不断的判断是否有任务须要执行
# celery -A website beat -l info 复制代码
1.若是你同时使用了异步任务和计划任务,有一种更简单的启动方式celery -A website worker -b -l info
,可同时启动worker和beat 2.若是使用的不是rabbitmq作队列那么须要在主配置文件中website/celery.py
配置broker和backend,以下:
# redis作MQ配置 app = Celery('website', backend='redis', broker='redis://localhost') # rabbitmq作MQ配置 app = Celery('website', backend='amqp', broker='amqp://admin:admin@localhost') 复制代码
3.celery不能用root用户启动的话须要在主配置文件中添加platforms.C_FORCE_ROOT = True
4.celery在长时间运行后可能出现内存泄漏,须要添加配置CELERYD_MAX_TASKS_PER_CHILD = 10
,表示每一个worker执行了多少个任务就死掉
相关文章推荐阅读