我们经常需要定时的执行某个任务,在Linux下我们有强大的crontab

我们经常需要定时执行某个任务,在linux下有强大的crontab,在python里除了第三方模块外,python自带了sched模块和Timer类,用于完成周期任务。timer类在threading模块里。

下面主要说明sched模块的使用

scheduler.scheduler(timefunc, delayfunc)

scheduler对像有如下方法和属性:

scheduler.enterabs(time,priority,action,argument)   生成一个调度事件,它的返回值可用于取消这个调度事件.相同时间执行的事件将按它们的优先级顺序处理

scheduler.enter(delay,priority,action,argument)     生成一个调度事件,返回值和enterabs一样

scheduler.cancel(event)    取消一个调度事件,参数为enterabs,enter的返回值。

scheduler.empty()    判断调度事件队列是否为空,空则返回True

scheduler.run()     运行所有调度事件,阻塞等待完成。这个方法使用构造方法中的delayfunc阻塞等下一个事件,然后执行它直至完成调度队列里的所有调度事件。cancel方法和run方法需不在一个线程里,如果在同一个线程需要在run之前cancel调度事件

scheduler.queue    调度队列



sched模块是一个延时调度处理模块,每次要执行某个任务时都必须写入一个调度任务(调用的方法)。

使用如下:

  1. 生成一个调度器:

    import time,sched

    s=sched.scheduler(time.time,time.sleep)

    说明:第一个参数必须是不带参数的时间函数,并且必须返回数字,比如此例返回的是一个时间戳,第二个参数是阻塞函数,该函数需带一个参数,兼容时间函数的输出。

  2. 添加第一调度事件:

    添加调度事件的方法有2个enter和enterabs,以enter为例:


    def print_time():

        print "From print_time", time.time()

    s.enter(5,1,print_time,())

  3. 执行

    s.run()

    需要注意的是sched模块不是循环的,一次调度被执行完后就结束了,如果要再执行,请再次enter, enter后也无需再次执行run.若在一个方法里重复调用run,当超过最大的递归深度时会导致异常,终止任务执行

    

#! /usr/bin/env python
#coding=utf-8
import time, os, sched 
    
# 第一个参数确定任务的时间,返回从某个特定的时间到现在经历的秒数 
# 第二个参数以某种人为的方式衡量时间 
schedule = sched.scheduler(time.time, time.sleep) 
    
def run_command(cmd, inc): 
    # 安排inc秒后再次运行自己,即周期运行 
    schedule.enter(inc, 0, run_command, (cmd, inc)) 
    os.system(cmd) 
        
def timming_exe(cmd, inc = 60): 
    # enter用来安排某事件的发生时间,从现在起第n秒开始启动 
    schedule.enter(inc, 0, run_command, (cmd, inc)) 
    # 持续运行,直到计划时间队列变成空为止 
    schedule.run() 
        
    
print("show time after 10 seconds:") 
if os.name == "nt":
    timming_exe("echo %time%", 10)
elif os.name=="posix":
    timming_exe("echo `date`", 10)