如果方法正在执行,请重复此步骤

2024-03-29 06:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以中断执行一个方法,并在超时的情况下重复它?你知道吗

例如连接到某个服务器的方法连接。你知道吗

try:
    connection(server,5)
except:
    repeat

假设方法连接运行超过5秒。然后我想提出异常并重复它。不需要例外我只想重复一遍。你知道吗

我正在考虑创建第二个线程来检查时间,当时间结束时,提供另一个线程中的方法中断,但我认为应该有一个更简单的解决方案。你知道吗


Tags: 方法服务器server时间情况解决方案connection线程
2条回答

或者,也可以使用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

相关问题 更多 >