celery任務調度模塊
安裝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任務調度模塊