當前位置:首頁 » 編程語言 » 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程序設計有所幫助。

熱點內容
4000以內二手安卓機怎麼選 發布:2025-07-15 05:11:25 瀏覽:643
靜態編譯修復器 發布:2025-07-15 05:11:24 瀏覽:505
iphonexr的存儲空間 發布:2025-07-15 05:09:20 瀏覽:327
能緩存航海王 發布:2025-07-15 04:55:38 瀏覽:90
安卓手機投屏為什麼只能本地視頻 發布:2025-07-15 04:51:19 瀏覽:537
棧的存儲結構 發布:2025-07-15 04:51:16 瀏覽:233
現在天龍八部腳本 發布:2025-07-15 04:45:35 瀏覽:332
優酷緩存後怎麼豎屏觀看 發布:2025-07-15 04:44:09 瀏覽:247
蟻周演算法 發布:2025-07-15 04:34:28 瀏覽:600
電腦伺服器名稱寫什麼 發布:2025-07-15 04:29:53 瀏覽:430