1. 指定特定時間運行某一任務,可以通過如下方式:
- from apscheduler.scheduler import Scheduler
- sched = Scheduler()
- sched.daemonic = False
- def job_function(text):
- print text
- from datetime import datetime
- job = sched.add_date_job(job_function, datetime(2012, 04, 12, 10, 13, 59), ['Hello World'])
- sched.start()
2. 有些時候,我們需要每隔一定時間運行一下任務Interval-based scheduling的方式,如下:
- from apscheduler.scheduler import Scheduler
- sched = Scheduler()
- sched.daemonic = False
- def job_function():
- print "Hello World"
- sched.add_interval_job(job_function, hours=2)
- sched.add_interval_job(job_function, hours=2, start_date='2012-04-12 09:51:59')
- sched.start()
除此之外,也可以使用Decorator的方式,如下:
- from apscheduler.scheduler import Scheduler
- sched = Scheduler()
- sched.daemonic = False
- sched.start()
- @sched.interval_schedule(hours=2, start_date='2012-04-12 09:54:59')
- def job_function():
- print "Hello World"
如果想解除Decorator功能方法,可以通過如下方式:
- scheduler.unschedule_job(job_function.job)
3. 如果我們想實現類似Linux下的crontab功能,可以通過Cron-style scheduling方式來實現,如下:
- from apscheduler.scheduler import Scheduler
- sched = Scheduler()
- sched.daemonic = False
- def job_function():
- print "Hello World"
- # Schedules job_function to be run on the third Friday
- # of June, July, August, November and December at 00:00, 01:00, 02:00 and 03:00
- sched.add_cron_job(job_function, month='6-8,11-12', day='3rd fri', hour='0-3')
- sched.start()
同樣,也可以通過Decorator方式來實現,如下:
- from apscheduler.scheduler import Scheduler
- sched = Scheduler()
- sched.daemonic = False
- sched.start()
- @sched.cron_schedule(day='last sun')
- def some_decorated_task():
- print "I am printed at 00:00:00 on the last Sunday of every month!"
apscheduler會創建一個線程,這個線程默認是daemon=True,也就是默認的是線程守護的,這裡設置為False只是為了方便看到效果。除此之外apscheduler也提供其他的選項,如threadpool和jobstores等功能,大家可以自己進行相關的探索學習,相關API可以參考:http://packages.python.org/APScheduler/genindex.html