Python之Scheduler框架浅析
Python的Scheduler框架是模仿Java的Quartz框架写的,用起来还是比较不错的,这里向大家强烈推荐下。下载地址:http://pypi.python.org/pypi/APScheduler/2.0.3
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
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20