celery定時執行任務 的使用
1 參照部落格https://www.cnblogs.com/xiaonq/p/9303941.html#i1
1 建立celery_pro包 # 可在任意檔案下
2 在 celery_pro 下建立 celery.py 檔案
# -*- coding:utf8 -*- from __future__ import absolute_import, unicode_literals #1. absolute_import 可以使匯入的celery是python絕對路基的celery模組,不是當前我們建立的celery.py #2. unicode_literals 模組可能是python2和3相容的,不知道 from celery import Celery # from .celery import Celery #這樣才是匯入當前目錄下的celery app = Celery('proj', broker='redis://localhost', backend='redis://localhost', include=['celery_pro.tasks', ]) #celery-pro是存放celery檔案的資料夾名字 #例項化時可以新增下面這個屬性 app.conf.update( result_expires=3600, #執行結果放到redis裡,一個小時沒人取就丟棄 ) import time # 配置定時任務:每5秒鐘執行 呼叫一次celery_pro下tasks.py檔案中的add函式 app.conf.beat_schedule = { 'add-every-5-seconds': { 'task': 'celery_pro.tasks.add', 'schedule': 5.0, 'args': (16, 16), }, } app.conf.timezone = 'UTC' if __name__ == '__macelery -A celery_pro beat -l infoin__': app.start()
3 建立 tasks.py 檔案
# -*- coding:utf8 -*- from __future__ import absolute_import, unicode_literals from .celery import app #從當前目錄匯入app #寫一個add函式 @app.task def add(x, y): print('執行函式') return x + y
執行下面兩條命令即可讓celery定時執行任務了
1、啟動一個worker:在celery_pro外層目錄下執行
celery -A celery_pro worker -l info
2、啟動任務排程器 celery beat
celery -A celery_pro beat -l info
3、執行效果
看到celery執行日誌中每5秒回返回一次 add函式執行結果
3、啟動celery的worker:每臺機器可以啟動8個worker
1、在pythondir目錄下啟動/pythondir/celery_pro/目錄下的worker
celery -A celery_pro worker -l info
2、後臺啟動worker:/pythondir/celery_pro/目錄下執行
celery multi start w1 -A celery_pro -l info#
celery multi start w1 w2 -A celery_pro -l info#一次性啟動w1,w2兩個worker
celery -A celery_pro status#檢視當前有哪些worker在執行
celery multi stop w1 w2 -A celery_pro#停止w1,w2兩個worker
celery multi restart w1 w2 -A celery_pro#重啟w1,w2兩個worker