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

熱點內容
什麼是法人賬號密碼 發布:2025-07-15 10:34:59 瀏覽:874
編程題抽獎 發布:2025-07-15 10:34:00 瀏覽:629
linux手動編譯的內核怎麼刪 發布:2025-07-15 10:31:56 瀏覽:96
存儲行業發展趨勢 發布:2025-07-15 10:25:22 瀏覽:242
怎麼刪除配置提示 發布:2025-07-15 10:21:27 瀏覽:245
java深入學習 發布:2025-07-15 10:13:50 瀏覽:535
linux應用程序開發pdf 發布:2025-07-15 10:11:37 瀏覽:911
解壓冷知識 發布:2025-07-15 10:11:35 瀏覽:78
outlook郵件的伺服器是什麼 發布:2025-07-15 09:45:59 瀏覽:482
如何安排資產配置 發布:2025-07-15 09:33:24 瀏覽:906