celery
- 官方網(wǎng)站
- 中文文檔
- 示例一:用戶發(fā)起request,并等待response返回。在本些views中,可能需要執(zhí)行一段耗時(shí)的程序,那么用戶就會(huì)等待很長時(shí)間,造成不好的用戶體驗(yàn)
- 示例二:網(wǎng)站每小時(shí)需要同步一次天氣預(yù)報(bào)信息,但是http是請(qǐng)求觸發(fā)的,難道要一小時(shí)請(qǐng)求一次嗎?
- 使用celery后,情況就不一樣了
- 示例一的解決:將耗時(shí)的程序放到celery中執(zhí)行
- 示例二的解決:使用celery定時(shí)執(zhí)行
名詞
- 任務(wù)task:就是一個(gè)Python函數(shù)
- 隊(duì)列queue:將需要執(zhí)行的任務(wù)加入到隊(duì)列中
- 工人worker:在一個(gè)新進(jìn)程中,負(fù)責(zé)執(zhí)行隊(duì)列中的任務(wù)
- 代理人broker:負(fù)責(zé)調(diào)度,在布置環(huán)境中使用redis
使用
celery==3.1.25
celery-with-redis==3.0
django-celery==3.1.17
INSTALLED_APPS = (
...
'djcelery',
}
...
import djcelery
djcelery.setup_loader()
BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_IMPORTS = ('應(yīng)用名稱.task')
- 在應(yīng)用目錄下創(chuàng)建task.py文件
import time
from celery import task
@task
def sayhello():
print('hello ...')
time.sleep(2)
print('world ...')
- 遷移,生成celery需要的數(shù)據(jù)表
python manage.py migrate
sudo redis-server /etc/redis/redis.conf
python manage.py celery worker --loglevel=info
function.delay(parameters)
#from task import *
def sayhello(request):
print('hello ...')
import time
time.sleep(10)
print('world ...')
# sayhello.delay()
return HttpResponse("hello world")
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。