Python-如果1分钟内没有发生任何事情,请继续执行代码



我正在编写一个脚本,该脚本通过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个小时左右,设备就会重新启动,在重新启动期间,我的功能启动请求不会运行,我的代码也会完全停止。

我的问题是,有没有办法告诉python:"如果1分钟内没有发生任何事情,请重试";

目前尚不清楚ws究竟是什么,也不清楚如何设置;但是您想在套接字中添加一个超时。

https://websockets.readthedocs.io/en/stable/api.html#websockets.client.connect具有timeout关键字;有关其功能的详细信息,请参阅文档。

如果这不是您正在使用的websocket库,请用详细信息更新您的问题。

您可以从time模块使用sleep

import time
time.sleep(60) # waits for 1 minute

此外,对于sleep,请考虑Multithreading

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.sleen(0.75(分别暂停这两个线程的执行0.5秒和0.7秒。

点击此处了解更多

最新更新