[英]Terminating a python thread from within based on a timer
I have tried to solve this problem through multiple forums and still have not got a solution to the answer. 我试图通过多个论坛解决此问题,但仍未找到答案的解决方案。 I'll try to be as specific as possible as to what I am looking for.
我将针对所要寻找的内容尽可能地具体。 I have a use case where I need to have a thread terminate itself after a certain time out.
我有一个用例,我需要让某个线程在一段时间后终止。 I do not want to use .join(timeout=x) from the main thread because that as I understand does not terminate the thread.
我不想从主线程使用.join(timeout = x),因为据我所知不会终止线程。 I want this timed event to be realized within the thread and it should do some clean up and updates before it terminates itself.
我希望在线程中实现此定时事件,并且它应该在终止之前进行一些清理和更新。 JFYI: I can't use a loop wothin the run method to check for a state.
JFYI:我不能在run方法中使用循环来检查状态。 My need is that the target function will be called within the run method.
我需要在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.
Here is another way using eventlet.timeout
. 这是使用
eventlet.timeout
另一种方法。 The target_function
below is the main logic in the Thread.run
block. 下面的
target_function
是Thread.run
块中的主要逻辑。 When time is up, it throws a pre-defined exception. 时间到时,它将引发预定义的异常。 You can add your internal cleanup logic block in the
cleanup
function. 您可以在
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()
I hope it meets your requirements. 我希望它能满足您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.