http://www.mamicode.com/info-detail-1798782.htmlhtml
https://blog.csdn.net/lu1005287365/article/details/52315786python
本系列文章的开发环境:web
window 7 + python2.7 + pycharm5 + celery3.1.25 + django1.9.4
在咱们平常的开发工做中,常常会遇到这几种状况:数据库
一、在web应用中,用户触发一个操做,执行后台处理程序,这个程序须要执行很长时间才能返回结果。怎样才能不阻塞http请求,不让用户等待从而提升用户体验呢? 二、定时任务脚本:生产环境常常会跑一些定时任务脚本,假如你有上千台的服务器、上千种任务,定时任务的管理很困难,如何对job进行有效的管理? 三、异步需求:好比发送短信/邮件、推送消息、清理/设置缓存?
若是你有以上的需求,那么Celery可能对你颇有用。django
Celery是一个能够处理大量消息的分布式任务系统,它凭借简单、灵活、可靠的特性被普遍使用。Celery聚焦于实时处理任务,同时也支持定时的任务调度。json
从上图中能够知道Celery包含以下组件:缓存
这里Broker和Result Backend都选择RabbitMQ。服务器
2) 安装Celery 3.1.25并发
为何选择这个低版本?请见最下面的问题列表。
pip install celery==3.1.25
2.1) 在一个目录中建立tasks.py文件,内容以下:
from celery import Celery
#建立celery实例,其中backend表示采用rpc瞬态信息,不保存到数据库;broker表示链接RabbitMQ URL app = Celery(‘tasks‘,backend=‘rpc://‘,broker=‘pyamqp://guest@localhost//‘) @app.task def hello(): return "hello celery"
2.2) 启动celery worker
到tasks.py文件那层目录,执行如下命令:
celery -A tasks worker --loglevel=info
启动输出信息以下:
E:\workdir\test_pro>celery -A tasks worker --loglevel=info [2017-05-10 18:26:18,298: WARNING/MainProcess] c:\python27\lib\site-packages\celery\apps\worker.py:161: CDeprecationWarnin Starting from version 3.2 Celery will refuse to accept pickle by default. The pickle serializer is a security concern as it may give attackers the ability to execute any command. It‘s important to secure your broker from unauthorized access when using pickle, so we think that enabling pickle should require a deliberate action and not be the default choice. If you depend on pickle then you should set a setting to disable this warning and to be sure that everything will continue working when you upgrade to Celery 3.2:: CELERY_ACCEPT_CONTENT = [‘pickle‘, ‘json‘, ‘msgpack‘, ‘yaml‘] You must only enable the serializers that you will actually use. warnings.warn(CDeprecationWarning(W_PICKLE_DEPRECATED)) -------------- celery@507B9D97E083 v3.1.25 (Cipater) ---- **** ----- --- * *** * -- Windows-7-6.1.7601-SP1 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: tasks:0x35fc240 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: rpc:// - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- --- ***** ----- [queues] -------------- .> celery exchange=celery(direct) key=celery [tasks] . tasks.hello [2017-05-10 18:26:18,433: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2017-05-10 18:26:18,483: INFO/MainProcess] mingle: searching for neighbors [2017-05-10 18:26:19,497: INFO/MainProcess] mingle: all alone [2017-05-10 18:26:19,523: WARNING/MainProcess] celery@507B9D97E083 ready.
2.3) 测试结果
另起一个终端,仍是到tasks.py那层目录,进入python命令行:
这时celery worker会有提示信息:
到此为止,celery入门就介绍到这里了,下一节介绍如何在django中使用celery。