python定时执行详解

知识点

1. sched模块,准确的说,它是一个调度(延时处理机制),每次想要定时执行某任务都必须写入一个调度。

(1)生成调度器:
s = sched.scheduler(time.time,time.sleep)
第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。可以说sched模块设计者是“在下很大的一盘棋”,比如第一个函数可以是自定义的一个函数,不一定是时间戳,第二个也可以是阻塞socket等。
(2)加入调度事件
其实有enter、enterabs等等,我们以enter为例子。
s.enter(x1,x2,x3,x4)
四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数,给他的参数(注意:一定要以tuple给如,如果只有一个参数就(xx,))
(3)运行
s.run()
注意sched模块不是循环的,一次调度被执行后就Over了,如果想再执行,请再次enter

2. time模块,它是python自带的模块,主要用于时间的格式转换和处理。

time.sleep(s)

推迟调用线程的运行,s指秒数

3. os模块也是python自带的模块,os模块中的system()函数可以方便地运行其他程序或者脚本。

os.system(cmd)
cmd 为要执行的命令,近似于Windows下cmd窗口中输入的命令。

下面我们来看具体实例:

1.定时任务代码

#定时执行任务命令
import time,os,sched
schedule = sched.scheduler(time.time,time.sleep)
def perform_command(cmd,inc):
    os.system(cmd)
    print('task')
def timming_exe(cmd,inc=60):
    schedule.enter(inc,0,perform_command,(cmd,inc))
    schedule.run()
print('show time after 2 seconds:')
timming_exe('echo %time%',2)

2.周期性执行任务

import time,os,sched
schedule = sched.scheduler(time.time,time.sleep)
def perform_command(cmd,inc):
    #在inc秒后再次运行自己,即周期运行
    schedule.enter(inc, 0, perform_command, (cmd, inc))
    os.system(cmd)
def timming_exe(cmd,inc=60):
    schedule.enter(inc,0,perform_command,(cmd,inc))
    schedule.run()#持续运行,直到计划时间队列变成空为止
print('show time after 2 seconds:')
timming_exe('echo %time%',2)

3.循环执行命令

import time,os
def re_exe(cmd,inc = 60):
    while True:
        os.system(cmd)
        time.sleep(inc)
re_exe("echo %time%",5)
原文地址:https://www.cnblogs.com/huny/p/13430894.html