关于定时执行命令,在linux中有crontab简单易用
但是想要在python这个粒度下做的话,当然可以利用一个死循环来做
死循环
import os
import time
def test():
while True:
now = time.strftime('%H:%M')
print now
if '12:00'<now<'13:00':
os.system("cmd")
高端点可以使用sched模块
sched模块
sched模块使用方法:
1.初始化一个scheduler实例
2.enter/enterabs 安排某事件的发生时间
enter(time, priority, action, argument) 这里的time是相对时间,执行到这里相对多久执行action,argument是action的参数。
enterabs(time, priority, action, argument) time则是一个绝对时间,其余同上
3.run
run()一直被阻塞, 直到所有事件被全部执行完. 每个事件在同一线程中运行, 所以如果一个事件的执行时间大于其他事件的延迟时间,那么, 就会产生重叠. 重叠的解决方法是推迟后来事件的执行时间. 这样保证没有丢失任何事件, 但这些事件的调用时刻会比原先设定的迟。
enter例子
import time,os,sched
scheduler=sched.scheduler(time.time,time.sleep)
def perform_command(cmd,inc):
os.system(cmd)
def timming_exe(cmd,inc=5):
scheduler.enter(inc,0,perform_command,(cmd,inc))
scheduler.run()
if __name__=="__main__":
print("show time after 5 seconds:")
timming_exe("ls -l *.py",5)
固定在每天执行的例子
import sched,time
scd=sched.scheduler(time.time,time.sleep)
def each_day_time(hour,min,sec,next_day=True):
struct=time.localtime()
if next_day:
day=struct.tm_mday+1
else:
day=struct.tm_mday
return time.mktime((struct.tm_year,struct.tm_mon,day,hour,min,sec,struct.tm_wday,
struct.tm_yday,struct.tm_isdst))
def echo_test_msg():
scd.enterabs(each_day_time(15,2,2,True),1,echo_test_msg,())
print time.localtime()
print "---------------test----------------"
def main():
scd.enterabs(each_day_time(15,2,2,False),1,echo_test_msg,())
scd.run()
if __name__=="__main__":
main()
事件取消例子
#coding=utf-8
import sched
import threading
import time
scheduler = sched.scheduler(time.time, time.sleep)
counter = 0 #一个全局变量的计数器
def increment_counter(name):
global counter
print 'EVENT:', time.time(), name
counter += 1
print 'NOW:', counter
if __name__=="__main__":
print 'START:', time.time()
e1 = scheduler.enter(2, 1, increment_counter, ('E1',))
e2 = scheduler.enter(3, 1, increment_counter, ('E2',))
t = threading.Thread(target=scheduler.run)
#enter()和enterabs()返回一事件的引用, 该引用可被用于事件的取消. 由于run()阻塞,
#所以事件的取消操作需要在另外一个线程中进行. 如下例子, 在一个子线程开始执行调度, 而主处理线程用于取消某个事件
t.start()
scheduler.cancel(e1) #取消了e1的那个调度
t.join() #等调度完成再开始下一个
print 'FINAL:', counter
Timer模块
较sched更为高级,因为sched只是支持在单线程的环境里面使用;对于多线程,考虑到安全性等,使用threading.Timer更为恰当。
只需要Timer(5, print_time, ( time.time(), )).start() ,Timer自动执行了,不需要再放到盒子里,然后一下子.run一下,另外,也不需要分优先级,可以同时处理喔,为了显示多线程同时处理的效果