python分布式任務排程Celery

2022-09-03 10:09:10 字數 1925 閱讀 1219

celery是python開發的分布式任務排程模組,今天抽空看了一下,果然介面簡單,開發容易,5分鐘就寫出了乙個非同步傳送郵件的服務。

celery本身不含訊息服務,它使用第三方訊息服務來傳遞任務,目前,celery支援的訊息服務有rabbitmq、redis甚至是資料庫,當然redis應該是最佳選擇。

用pip或easy_install安裝:

$ sudo pip install celery

或著:

$ sudo easy_install celery

使用redis作為broker時,再安裝乙個celery-with-redis。

開始編寫tasks.py:

# tasks.py

import time

from celery import celery

celery = celery('tasks', broker='redis://localhost:6379/0')

@celery.task

def sendmail(mail):

print('sending mail to %s...' % mail['to'])

time.sleep(2.0)

print('mail sent.')

然後啟動celery處理任務:

$ celery -a tasks worker --loglevel=info

上面的命令列實際上啟動的是worker,如果要放到後台執行,可以扔給supervisor。

如何傳送任務?非常簡單:

>>> from tasks import sendmail

>>> sendmail.delay(dict(to='[email protected]'))

1a0a9262-7858-4192-9981-b7bf0ea7483b>

可以看到,celery的api設計真的非常簡單。

然後,在worker裡就可以看到任務處理的訊息:

[2013-08-27 19:20:23,363: warning/mainprocess] [email protected] ready.

[2013-08-27 19:20:23,367: info/mainprocess] consumer: connected to redis://localhost:6379/0.

[2013-08-27 19:20:45,618: info/mainprocess] got task from broker: tasks.sendmail[1a0a9262-7858-4192-9981-b7bf0ea7483b]

[2013-08-27 19:20:45,655: warning/poolworker-4] sending mail to [email protected]...

[2013-08-27 19:20:47,657: warning/poolworker-4] mail sent.

[2013-08-27 19:20:47,658: info/mainprocess] task tasks.sendmail[1a0a9262-7858-4192-9981-b7bf0ea7483b] succeeded in 2.00266814232s: none

celery預設設定就能滿足基本要求。worker以pool模式啟動,預設大小為cpu核心數量,預設序列化機制是pickle,但可以指定為json。由於python呼叫unix/linux程式實在太容易,所以,用celery作為非同步任務框架非常合適。

celery還有一些高階用法,比如把多個任務組合成乙個原子任務等,還有乙個完善的監控介面,以後有空再繼續研究。

分布式任務排程

定時job,在什麼時間進行執行 任務。public static void main string args catch exception e thread thread new thread runnable thread.start public static void main string...

分布式排程系統 任務排程

這就是分布式任務排程所要解決的問題 舉個栗子 如何快速的做出大量的熱狗?如果將每乙個乙個熱狗按流程做的話,可見工作量會十分巨大而且效率低下 對任務按需求切分成多個子任務 再對所有的中間態結果進行reduce合併,得到最終結果 我們換個角度理解mapreduce操作 還會有一些廚師,按照一定的比例,將...

quartz的分布式任務排程

在實際的併發量較高的專案中,架構師通常會對伺服器進行集群或者對專案架構進行分布式部署 請允許筆者模擬乙個場景 某專案構架採用了nginx進行三颱應用型伺服器的負載均衡,並且每台伺服器部署同一套 這裡顯然要對quartz相應的進行集群 假設,該專案中存在乙個定時器模組 如果這裡不做特殊處理的話,三颱應...