[英]Terminating a python thread from within based on a timer
我试图通过多个论坛解决此问题,但仍未找到答案的解决方案。 我将针对所要寻找的内容尽可能地具体。 我有一个用例,我需要让某个线程在一段时间后终止。 我不想从主线程使用.join(timeout = x),因为据我所知不会终止线程。 我希望在线程中实现此定时事件,并且它应该在终止之前进行一些清理和更新。 JFYI:我不能在run方法中使用循环来检查状态。 我需要在run方法中调用目标函数。
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
self.timer = Timer(5.0, self.timeout)
def run(self):
self.timer.start()
# call the target function which runs
def timeout(self):
# timeout code
# If timeout has been reached then thread should do some internal cleanup and terminate thread here.
这是使用eventlet.timeout
另一种方法。 下面的target_function
是Thread.run
块中的主要逻辑。 时间到时,它将引发预定义的异常。 您可以在cleanup
功能中添加内部清除逻辑块。
from eventlet.timeout import Timeout
from eventlet import sleep
class TimeoutError(Exception):
pass
def target_function(seconds=10):
print("Run target functions ...")
for i in range(seconds, -1, -1):
print("Count down: " + str(i))
sleep(1)
def cleanup():
print("Do cleanup ...")
timeout = Timeout(seconds=5, exception=TimeoutError)
try:
target_function(20)
except TimeoutError:
cleanup()
finally:
print("Timeout ...")
timeout.cancel()
我希望它能满足您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.