celery支持定時任務,設定好任務的執行時間,celery就會定時自動幫你執行, 這個定時任務模塊叫celery beat html
項目前提: 安裝並啓動Redis python
celery_Schedule.pylinux
# version: python3.2.5 # author: ‘lft415659‘ from celery import Celery from celery.schedules import crontab # 能夠實現複雜的定時任務 app = Celery('CelerySchedule', # redis://:password@hostname:port/db_number 有密碼認證的鏈接 broker='redis://192.168.2.105', # broker='redis://:密碼@192.168.2.105:6379/0', backend='redis://192.168.2.105', # 用於Celery的返回結果的接收 ) # 建立定時任務 @app.on_after_configure.connect # 啓動程序鏈接上celery後自動執行這個函數生成定時任務 def setup_periodic_tasks(sender, **kwargs): # 第一次參數必須是sender,是定時任務的一個實例 # Calls test('hello') every 10 seconds. 這裏的test是咱們自定義的函數 sender.add_periodic_task(10.0, test.s('hello'), name='add every 10') # Calls test('world') every 30 seconds sender.add_periodic_task(30.0, test.s('world'), expires=10) # Executes every Monday morning at 7:30 a.m. 更復雜的定時任務 sender.add_periodic_task( crontab(hour=7, minute=30, day_of_week=1), test.s('Happy Mondays!'), ) @app.task def test(arg): print('run task:', arg)
後臺啓動Celery的worker任務:redis
omc@omc-virtual-machine:~$ cd Celery omc@omc-virtual-machine:~/Celery$ vim celery_Schedule.py omc@omc-virtual-machine:~/Celery$ celery -A celery_Schedule worker -l info
啓動定時任務調度器[celery beat]sql
omc@omc-virtual-machine:~/Celery$ celery -A celery_Schedule beat
上面的定時任務比較簡單,只是每多少s執行一個任務,但若是你想要每週一三五的早上8點給你發郵件怎麼辦呢?哈,其實也簡單,用crontab功能,跟linux自帶的crontab功能是同樣的,能夠個性化定製任務執行時間 vim
【linux crontab】http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html app
【更多參考】http://www.cnblogs.com/alex3714/articles/6351797.html函數
from celery.schedules import crontab app.conf.beat_schedule = { # Executes every Monday morning at 7:30 a.m. 'add-every-monday-morning': { 'task': 'tasks.add', 'schedule': crontab(hour=7, minute=30, day_of_week=1), 'args': (16, 16), }, }
app.conf.beat_schedule = { 'add-every-30-seconds': { 'task': 'tasks.add', 'schedule': 30.0, 'args': (16, 16) }, } app.conf.timezone = 'UTC'