I modified the following code from first answer on this link.
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, target, timeout):
super(StoppableThread, self).__init__()
self._target = target
self._timeout = timeout
self._stop = threading.Event()
self.awake = threading.Event()
def run(self):
while(not self._stop.isSet()):
self.awake.clear()
time.sleep(self._timeout)
self.awake.set()
self._target()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
Once I create an instance of this class and set it to daemon process, I would like to terminate it at a later time, when the thread is sleeping, else wait for it to complete the _target()
function and then terminate. I am able to handle the latter case by calling stop method. However, I have no idea of terminating it when the _awake
event object is set to False
. Can someone please help?