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

 

本文出自 “放飞翅膀,追求梦想” 博客,请务必保留此出处http://flykite.blog.51cto.com/4721239/832036

你可能感兴趣的:(Python)