So, I have these two classes that I use to schedule functions in a timer. They work very well, but they will run in the program for very long periods of time, so I want to make sure that I clean the threads that “stop” correctly.
Can someone explain how I cleared these threads from threading._Timer since I use the setDaemon (True) flag.
How I will use these classes: I will create a class manager object and keep calling MyClassManager.add_oneTimeOperation (MyFunction, 5) over and over again ...
Thank!
class Operation(threading._Timer):
alive = True
def __init__(self, *args, **kwargs):
threading._Timer.__init__(self, *args, **kwargs)
self.setDaemon(True)
def run(self):
while (self.alive):
self.finished.clear()
self.finished.wait(self.interval)
if not self.finished.isSet():
self.function(*self.args, **self.kwargs)
else:
return
def run_once(self):
self.finished.clear()
self.finished.wait(self.interval)
if not self.finished.isSet():
self.function(*self.args, **self.kwargs)
else:
return
self.finished.set()
def cancel(self):
self.finished.set()
self.alive = False
class Manager(object):
ops = []
def add_operation(self, operation, interval, args=[], kwargs={}):
op = Operation(interval, operation, args, kwargs)
self.ops.append(op)
thread.start_new_thread(op.run, ())
def add_oneTimeOperation(self, operation, interval, args=[], kwargs={}):
op = Operation(interval, operation, args, kwargs)
self.ops.append(op)
thread.start_new_thread(op.run_once, ())
def stop(self):
for op in self.ops:
op.cancel()
def clear_operations(self):
del self.ops[:]
source
share