Celery是Python開發的分佈式任務調度模塊,Celery本身不含消息服務,它使用第三方消息服務來傳遞任務,目前,Celery支持的消息服務有RabbitMQ、Redis甚至是數據庫。
安裝celery
pip install Celery
當使用redis時需要再安裝celery-with-redis
celery的tasks腳本編寫
例子:
import time
from celery import Celery
#指定redis的地址和庫
broker='redis://localhost:6379/0'
backend='redis://localhost:6379/1'
#指定名字
celery = Celery('tasks', broker=broker, backend=backend)
@celery.task
def add(x, y):
return x+y
def sendmail(mail):
print('sending mail to %s...' % mail['to'])
time.sleep(2.0)
print('mail sent.')
啓動task任務
#需要將task任務部署到linux服務器上,並將此任務運行,如果爲運行此任務,則無法向redis傳入值,也無法監控返回狀態,執行命令如下
celery -A tasks worker -l info
調用celery接口
例子:
from celery_task import add,sendmail
import time
a = add.delay(10, 20)
print (a)
print (type(a))
time.sleep(1)
#查看celery返回的結果
print (a.result)
#查看celery的返回狀態
print (a.status)
#指定超時時間爲10秒
print (a.get(timeout=10))
#是否處理完成
print (a.ready())
#調用sendmail
sendmail.delay(dict(to='[email protected]'))
celery多任務處理
celeryconfig.py
#celery多任務的配置文件,需要放到服務器中
from kombu import Exchange,Queue
#需要按照celery格式
BORKER_URL = "redis://192.168.1.1:6379/1"
CELERY_RESULT_BACKEND = "redis://192.168.1.1/2"
CELERY_QUEUES = {
Queue("default", Exchange("default"), routing_key=("default")),
Queue("for_task_A", Exchange("for_task_A"), routing_key=("for_task_A")),
Queue("for_task_B", Exchange("for_task_B"), routing_key=("for_task_B"))
}
CELERY_ROUTES = {
"celery_practice.taskA":{"queue":"for_task_A", "routing_key":"for_task_A"},
"celery_practice.taskB":{"queue":"for_task_B", "routing_key":"for_task_B"}
}
#celery定時任務
CELERY_TIMEZONE = 'UTC'
CELERYBEAT_SCHEDULE = {
'taskA_schedule':{
'task':'celery_practice.taskA',
#暫停時間
'schedule':20,
'args':(5, 6)
},
'taskB_schedule':{
'task':'celery_practice.taskB',
'schedule':50,
'args':(100, 200, 300)
}
'add_schedule': {
'task': 'celery_practice.add',
'schedule': 10,
'args': (10, 20)
}
}
celery_practice.py
#多任務內容,也需要放到服務器上運行
from celery import Celery
app = Celery()
#同celery多任務配置文件腳本名
app.config_from_object("celeryconfig")
@app.task
def taskA(x, y):
return x*y
@app.task
def taskB(x, y, z):
return x+y+z
@app.task
def add(x, y):
return x+y
celery_practice1.py
#具體客戶端程序
from celery_practice import *
r1 = taskA.delay(10, 20)
print (r1.result)
r2 = taskB.delay(1, 2, 3)
print (r2.result)
r3 = add.delay(5, 10)
print (r3.status)
linux服務器上需要運行內容
celery -A celery_practice worker -l info -n workerA.%h -Q for_task_A
celery -A celery_practice worker -l info -n workerB.%h -Q for_task_B
celery -A celery_practice beat