有没有办法中断执行方法并在超时的情况下重复执行该方法?
例如连接到某个服务器的方法连接。
try:
connection(server,5)
except:
repeat
让我们看一下方法连接运行超过5秒的情况。 然后,我想提出例外情况并重复一遍。 例外是没有必要的,我只想重复一遍。
我正在考虑创建第二个线程来检查时间,并且在超时后提供另一个线程中的方法中断,但是我认为应该有一个更简单的解决方案。
或者,您也可以使用while循环:
def connection(server, timeout):
while everything_ok:
try:
# do stuff
except Exception:
continue
break
当然,如果连接是您的方法,而不是某些第三方库提供的方法。
您可以使用线程。
码:
import threading
success = False
def connect():
global success
connection(server,5)
success = True
th = threading.Thread(target=connect)
th.start()
time.sleep(5) #timeout 5 sec
if success:
yuhuuu
else:
th.stop() #kill task