当前位置:首页 » 编程语言 » pythonrun函数

pythonrun函数

发布时间: 2023-12-29 18:05:50

python每隔N秒运行指定函数的方法

python每隔N秒运行指定函数的方法
这篇文章主要介绍了python每隔N秒运行指定函数的方法,涉及Python的线程与时间操作技巧,非常具有实用价值,需要的朋友可以参考下
这是一个类似定时器的效果,每隔指定的秒数运行指定的函数,采用线程实现,代码简单实用。
代码如下: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
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)
希望本文所述对大家的Python程序设计有所帮助。

热点内容
java返回this 发布:2025-10-20 08:28:16 浏览:566
制作脚本网站 发布:2025-10-20 08:17:34 浏览:855
python中的init方法 发布:2025-10-20 08:17:33 浏览:555
图案密码什么意思 发布:2025-10-20 08:16:56 浏览:733
怎么清理微信视频缓存 发布:2025-10-20 08:12:37 浏览:656
c语言编译器怎么看执行过程 发布:2025-10-20 08:00:32 浏览:975
邮箱如何填写发信服务器 发布:2025-10-20 07:45:27 浏览:227
shell脚本入门案例 发布:2025-10-20 07:44:45 浏览:87
怎么上传照片浏览上传 发布:2025-10-20 07:44:03 浏览:777
python股票数据获取 发布:2025-10-20 07:39:44 浏览:683