APScheduler是基於Quartz(java實現的一個開源作業調度框架)的一個Python定時任務框架,實現了Quartz的所有功能,使用起來十分方便
項目地址 https://bitbucket.org/agronholm/apscheduler/
文檔 http://apscheduler.readthedocs.org/en/3.0/
簡單查看文檔
APScheduler has four kinds of components:
- triggers
- job stores
- executors
- schedulers
Here’s a quick guide for choosing a scheduler
- BlockingScheduler: use when the scheduler is the only thing running in your process
- BackgroundScheduler: use then you’re not using any of the frameworks below, and want the scheduler to run in the background inside your application
- AsyncIOScheduler: use if your application uses the asyncio module
- GeventScheduler: use if your application uses gevent
- TornadoScheduler: use if you’re building a Tornado application
- TwistedScheduler: use if you’re building a Twisted application
- QtScheduler: use if you’re building a Qt application
常見的幾種調度栗子
apschedules/examples/
https://bitbucket.org/agronholm/apscheduler/src/a6545cf29831bb6d8f055aeb2fa9d5204e9bd192/examples/?at=master
參照栗子,我可以迅速的寫出最常規的BlockingScheduler調度
from datetime import datetime
import os
from apscheduler.schedulers.blocking import BlockingScheduler
def tick():
print('Tick! The time is: %s' % datetime.now())
if __name__ == '__main__':
scheduler = BlockingScheduler()
scheduler.add_job(tick, 'interval', seconds=3)
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass
add_job函數這里有一個max_instances參數用於指定當前工作同時運行的實例數量,默認為1,
但是可能的上一個工作正在運行而未結束,那么下一個就認為失敗, 那么此時可以為一個特定的作業設置最大數量的調度程序
如:
scheduler.add_job(tick, 'interval', seconds=3, max_instances=6)
job.modify(max_instances=6, name='Alternate name')
更多的信息參考文檔以及examples。
