python定时调度

来源:互联网 发布:mysql 查看表的索引 编辑:程序博客网 时间:2024/06/05 08:23

网上很多关于APScheduler调用的例子,下面结合我在项目中的实际应用,来介绍一下它。APScheduler是基于Quartz的一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便。它提供了基于固定时间间隔、日期时间以及crontab类型的任务,并且可以持久化任务。

1.安装APScheduler 

安装过程很简单,可以基于easy_install安装easy_install apscheduler 

2.基于固定时间间隔

from apscheduler.scheduler import Schedulersched = Scheduler()@sched.interval_schedule(hours=3)def some_job():    print "Decorated job"sched.start()

3.基于日期时间

3.1基于日期
from datetime import datefrom apscheduler.scheduler import Scheduler# Start the schedulersched = Scheduler()sched.start()# Define the function that is to be executeddef my_job(text):    print text# The job will be executed on November 6th, 2009exec_date = date(2009, 11, 6)# Store the job in a variable in case we want to cancel itjob = sched.add_date_job(my_job, exec_date, ['text'])
3.2基于时间
from datetime import datetime# The job will be executed on November 6th, 2009 at 16:30:05job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])
3.3基于时间文本
job = sched.add_date_job(my_job, '2009-11-06 16:30:05', ['text'])# Even down to the microsecond level, if you really want to!job = sched.add_date_job(my_job, '2009-11-06 16:30:05.720400', ['text'])

3.4基于类crontab定时调度

#-*-coding:utf-8-*-  from apscheduler.scheduler import Scheduler    def job_function(a):      print a    if __name__ == '__main__':      hello = 'hello world'      sched = Scheduler(daemonic=False) # 注意这里,要设置 daemonic=False      sched.add_cron_job(job_function, day_of_week='mon-fri', hour='*', minute='0-59', second='*/5', args=[hello]) # args=[] 用来给job函数传递参数      sched.start()  

注意:APScheduler会创建一个线程,这个线程默认是daemon=True,也就是默认的是线程守护的。

在上面的代码里面,要是不加上sched.daemonic=False的话,这个脚本就不会运行。

因为上面的脚本要是没有sched.daemonic=False的话,它会创建一个守护线程。这个过程中,会创建scheduler的实例。但是由于脚本很小,运行速度很快,主线程mainthread会马上结束,而此时定时任务的线程还没来得及执行,就跟随主线程结束而结束了。(守护线程和主线程之间的关系决定的)。要让脚本运行正常,必须设置该脚本为非守护线程。sched.daemonic=False


4.关闭scheduler

sched.shutdown():默认方式,会等待线程池里面所有执行的任务结束才会shutdown.
sched.shutdown(wait=False):更快的方式

注意:
scheduler = Scheduler(standalone=True)
这种方式可以使scheduler在任务执行完成后退出,非常有用。
原创粉丝点击