下面是仿写代码:
import time
import threading
class TimeoutRequest:
def __init__(self, timeout=None):
self.timeout = timeout
def send_request(self, url):
def target():
# 模拟请求过程
time.sleep(5)
return "请求完成"
# 启动一个线程来执行请求
thread = threading.Thread(target=target)
thread.start()
# 等待线程完成或超时
thread.join(self.timeout)
if thread.is_alive():
raise Exception("请求超时!")
else:
return "请求结果"
# 使用 TimeoutRequest 类
try:
request = TimeoutRequest(timeout=3)
print(request.send_request("http://example.com"))
except Exception as e:
print(e) #
# 打印结果:'请求超时!'
在这个例子中,我们创建了一个
正如预期的那样,由于我们设置的模拟请求时间为5秒,而超时时间设置为3秒,所以在3秒后,请求还没有完成,因此触发了超时异常,并返回了 “请求超时!” 的消息。
这个简单的示例展示了如何使用 Python 的多线程和