[英]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.