python celery介紹和基本使用


08 python celery介紹和基本使用

 celery分布式任務隊列

RPC遠程,當執行一條命令,等待遠程執行結果返回客戶端。

在Linux上可以在后台執行,不影響其他任務執行。(涉及到異步)

 

1、分布式任務運算celery

參考:https://www.cnblogs.com/alex3714/p/6351797.html

任務計划:https://www.cnblogs.com/peida/archive/2013/01/08/2850483.html

 

  Crontab操作系統本身任務計划

Celery也可以實現定時任務,不需要操作系統。

Rabbitmq也可以實現異步。

 

   

2、測試代碼:

Celery在Windows上執行有問題,在Linux上使用。

 

  [root@backup testcleery]# celery -A celery_test worker -l debug 啟動過程中可能需要調整環境變量。export C_FORCE_ROOT=True

[root@backup testcleery]# export C_FORCE_ROOT=True

[root@backup testcleery]# celery -A celery_test worker -l info

 

  查看日志,任務模塊加載成功。Celery兩個模塊都已加載下來。

 

  測試celery模塊。

 

 3、測試同時啟動2個worker服務。

[root@backup testcleery]# export C_FORCE_ROOT=True

[root@backup testcleery]# celery -A celery_test worker -l info

[root@backup testcleery]# celery -A celery_test worker -l debug

兩個worker搶任務,隨機分發任務到worker。

 

  多開幾個終端進行測試,應用程序會隨機選擇worker。

 

4、來個復雜任務,按照生產情況,執行過程很長的服務

[root@backup testcleery]# vim celery_test2.py

 

  [root@backup testcleery]# celery -A celery_test2 worker -l info

root@backup testcleery]# python

>>> from celery_test2 import add,cmd

>>> t1 = cmd.delay('abcedef')

>>> t1.ready()

False

>>> t1.ready()

True

>>> t1.get()

1569491327.817837

>>> 

10s任務卡住了。

 

  當t1.ready()變成true,可以取值。

 

5、在項目中使用。指定項目文件。

[root@backup testcleery]# mkdir pro

[root@backup testcleery]# cd pro/

[root@backup pro]# pwd

/root/testcleery/pro

[root@backup pro]# touch __init__.py

 

  項目目錄結構和項目啟動方式。

[root@backup pro]#

生產項目編寫。

 

  [root@backup testcleery]# vim pro/celery.py

from __future__ import absolute_import, unicode_literals 

from celery import Celery  # 默認從Python絕對路徑引入celery包

配置認為列表項。

 

   啟動celery項目。

[root@backup testcleery]# celery -A pro worker -l debug

[root@backup testcleery]# python

Python 3.6.3 |Anaconda, Inc.| (default, Oct 13 2017, 12:02:49)

[GCC 7.2.0] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> from pro import tasks, tasks2

>>> t1 = tasks2.cmd('df')

running cmd... df

>>> t1=tasks.xsum.delay([1,2,4,3,2])

>>> t1.get()

12

>>> 

 Celery跟Django結合使用的比較多。后面章節重點講解。

Celery做定時任務。

后台啟動方式,

[root@backup testcleery]# celery multi start w1 -A pro worker -l info  啟動

[root@backup testcleery]# celery multi stop w1 -A pro worker -l info  關閉

 

  觀察到,一個worker任務有3個進程在跑。

https://www.cnblogs.com/alex3714/p/6351797.html

停止任務

 celery multi stopwait w1 -A proj -l info


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM