[英]Python - If nothing happens for 1 minute, proceed code
我正在編寫一個腳本,它通過 websocket 向設備發送串行消息。 當我想啟動我寫的設備時:
def start(ws):
"""
Function to send the start command
"""
print("start")
command = dict()
command["commandId"] = 601
command["id"] = 54321
command["params"] = {}
send_command(ws, command)
設備每隔 5 小時左右重新啟動一次,在重新啟動期間,我的 function 啟動請求沒有運行,我的代碼完全停止。
我的問題是,有沒有辦法告訴 python:“如果 1 分鍾沒有發生任何事情,請再試一次”
您可以使用time
模塊中的sleep
import time
time.sleep(60) # waits for 1 minute
另外,請考慮使用Multithreading
進行sleep
import threading
import time
def print_hello():
for i in range(4):
time.sleep(0.5)
print("Hello")
def print_hi():
for i in range(4):
time.sleep(0.7)
print("Hi")
t1 = threading.Thread(target=print_hello)
t2 = threading.Thread(target=print_hi)
t1.start()
t2.start()
上面的程序有兩個線程。 已使用 time.sleep(0.5) 和 time.sleep(0.75) 分別暫停這兩個線程的執行 0.5 秒和 0.7 秒。
目前尚不清楚ws
究竟是什么或如何設置它; 但是您想為套接字添加超時。
https://websockets.readthedocs.io/en/stable/api.html#websockets.client.connect有一個timeout
關鍵字; 有關其作用的詳細信息,請參閱文檔。
如果這不是您正在使用的 websocket 庫,請使用詳細信息更新您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.