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。