zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python每隔N秒运行指定的函数程序详解编程语言

Python程序编程语言 详解 函数 运行 指定 每隔
2023-06-13 09:20:24 时间

一个类似定时器的效果,每隔指定的秒数运行指定的函数,采用线程实现,代码简单实用。

import os 

import time 

def print_ts(message): 

 print "[%s] %s"%(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), message) 

def run(interval, command): 

 print_ts("-"*100) 

 print_ts("Command %s"%command) 

 print_ts("Starting every %s seconds."%interval) 

 print_ts("-"*100) 

 while True: 

 try: 

 # sleep for the remaining seconds of interval,http://www.sharejs.com 

 time_remaining = interval-time.time()%interval 

 print_ts("Sleeping until %s (%s seconds)..."%((time.ctime(time.time()+time_remaining)), time_remaining)) 

 time.sleep(time_remaining) 

 print_ts("Starting command.") 

 # execute the command 

 status = os.system(command) 

 print_ts("-"*100) 

 print_ts("Command status = %s."%status) 

 except Exception, e: 

 print e 

if __name__=="__main__": 

 interval = 5 

 command = r"ipconfig" 

 run(interval, command)

8390.html

cjava