I have some code similar to what's below. I have SomeClass
which starts a thread by calling MyThread
. The thread runs in a loop, but there can be very long delays in the loop (I've set the example to 120secs here). How do I go about interrupting the loop even while it's "sleeping" or idle waiting for the next for iterator? I can call the stop_thr
method, but this only stops the loop on the next iteration.
What's the best way to go about handling this?
class SomeClass
def __init__():
self.thr = MyThread()
self.thr.start()
def stop_thr():
self.thr.stop_thr()
class MyThread(threading.Thread)
def __init__(self, **kwargs)
super().__init__(**kwargs)
self.running = False
def run():
self.running = True
while self.running:
for x in range(1000):
# do stuff
sleep(120) # How do I interrupt this if signaled without waiting the full time?
if not self.running:
break # This works, but only after the 120secs elapses
def stop_thr():
self.running = False