Celery 官網:http://www.celeryproject.org/html
Celery 官方文檔英文版:http://docs.celeryproject.org/en/latest/index.htmlpython
Celery 官方文檔中文版:http://docs.jinkan.org/docs/celery/redis
Celery的架構由三部分組成,消息中間件(message broker)、任務執行單元(worker)和 任務執行結果存儲(task result store)組成。django
Celery自己不提供消息服務,可是能夠方便的和第三方提供的消息中間件集成。包括,RabbitMQ, Redis等等windows
Worker是Celery提供的任務執行的單元,worker併發的運行在分佈式的系統節點中。api
Task result store用來存儲Worker執行的任務的結果,Celery支持以不一樣方式存儲任務的結果,包括AMQP, redis等架構
異步執行:解決耗時任務併發
延遲執行:解決延遲任務app
定時執行:解決週期(週期)任務框架
pip install celery
消息中間件:RabbitMQ/Redis
app=Celery('任務名', broker='xxx', backend='xxx')
project ├── celery_task # celery包 │ ├── __init__.py # 包文件 │ ├── celery.py # celery鏈接和配置相關文件,且名字必須交celery.py │ └── tasks.py # 全部任務函數 ├── add_task.py # 添加任務 └── get_result.py # 獲取結果
# 1)建立app + 任務 # 2)啓動celery(app)服務: # 非windows # 命令:celery worker -A celery_task -l info # windows: # pip3 install eventlet # celery worker -A celery_task -l info -P eventlet # 3)添加任務:手動添加,要自定義添加任務的腳本,右鍵執行腳本 # 4)獲取結果:手動獲取,要自定義獲取任務的腳本,右鍵執行腳本 from celery import Celery broker = 'redis://127.0.0.1:6379/1' backend = 'redis://127.0.0.1:6379/2' app = Celery(broker=broker, backend=backend, include=['celery_task.tasks'])
from .celery import app import time @app.task def add(n, m): print(n) print(m) time.sleep(10) print('n+m的結果:%s' % (n + m)) return n + m @app.task def low(n, m): print(n) print(m) print('n-m的結果:%s' % (n - m)) return n - m
from celery_task import tasks # 添加當即執行任務 t1 = tasks.add.delay(10, 20) t2 = tasks.low.delay(100, 50) print(t1.id) # 添加延遲任務 from datetime import datetime, timedelta eta=datetime.utcnow() + timedelta(seconds=10) tasks.low.apply_async(args=(200, 50), eta=eta)
from celery_task.celery import app from celery.result import AsyncResult id = '21325a40-9d32-44b5-a701-9a31cc3c74b5' if __name__ == '__main__': async = AsyncResult(id=id, app=app) if async.successful(): result = async.get() print(result) elif async.failed(): print('任務失敗') elif async.status == 'PENDING': print('任務等待中被執行') elif async.status == 'RETRY': print('任務異常後正在重試') elif async.status == 'STARTED': print('任務已經開始被執行')
# 1)建立app + 任務 # 2)啓動celery(app)服務: # 非windows # 命令:celery worker -A celery_task -l info # windows: # pip3 install eventlet # celery worker -A celery_task -l info -P eventlet # 3)添加任務:自動添加任務,因此要啓動一個添加任務的服務 # 命令:celery beat -A celery_task -l info # 4)獲取結果 from celery import Celery broker = 'redis://127.0.0.1:6379/1' backend = 'redis://127.0.0.1:6379/2' app = Celery(broker=broker, backend=backend, include=['celery_task.tasks']) # 時區 app.conf.timezone = 'Asia/Shanghai' # 是否使用UTC app.conf.enable_utc = False # 任務的定時配置 from datetime import timedelta from celery.schedules import crontab app.conf.beat_schedule = { 'low-task': { 'task': 'celery_task.tasks.low', 'schedule': timedelta(seconds=3), # 'schedule': crontab(hour=8, day_of_week=1), # 每週一早八點 'args': (300, 150), } }
from .celery import app import time @app.task def add(n, m): print(n) print(m) time.sleep(10) print('n+m的結果:%s' % (n + m)) return n + m @app.task def low(n, m): print(n) print(m) print('n-m的結果:%s' % (n - m)) return n - m
from celery_task.celery import app from celery.result import AsyncResult id = '21325a40-9d32-44b5-a701-9a31cc3c74b5' if __name__ == '__main__': async = AsyncResult(id=id, app=app) if async.successful(): result = async.get() print(result) elif async.failed(): print('任務失敗') elif async.status == 'PENDING': print('任務等待中被執行') elif async.status == 'RETRY': print('任務異常後正在重試') elif async.status == 'STARTED': print('任務已經開始被執行')
""" celery框架django項目工做流程 1)加載django配置環境 2)建立Celery框架對象app,配置broker和backend,獲得的app就是worker 3)給worker對應的app添加可處理的任務函數,用include配置給worker的app 4)完成提供的任務的定時配置app.conf.beat_schedule 5)啓動celery服務,運行worker,執行任務 6)啓動beat服務,運行beat,添加任務 重點:因爲採用了django的反射機制,使用celery.py所在的celery_task包必須放置項目的根目錄下 """ # 1、加載django配置環境 import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "luffyapi.settings.dev") # 2、加載celery配置環境 from celery import Celery # broker broker = 'redis://127.0.0.1:6379/0' # backend backend = 'redis://127.0.0.1:6379/1' # worker app = Celery(broker=broker, backend=backend, include=['celery_task.tasks']) # 時區 app.conf.timezone = 'Asia/Shanghai' # 是否使用UTC app.conf.enable_utc = False # 任務的定時配置 from datetime import timedelta from celery.schedules import crontab app.conf.beat_schedule = { 'django-task': { 'task': 'celery_task.tasks.test_django_celery', 'schedule': timedelta(seconds=3), 'args': (), } }
from .celery import app # 獲取項目中的模型類 from api.models import Banner @app.task def test_django_celery(): banner_query = Banner.objects.filter(is_delete=False).all() print(banner_query)