所以我有两个类用于将函数安排到计时器中。 它们工作正常,但是它们将在一个程序中运行很长时间,所以我想确保我正在清理“停止”的线程 正确。
有人可以帮助解释我如何从threading._Timer清理这些线程,因为我使用了setDaemon(True)标志。
我将如何使用这些类: 我将创建一个类管理器的对象,并继续一遍又一遍地调用MyClassManager.add_oneTimeOperation(MyFunction,5)......
谢谢!
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
#self.finished.set()
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[:]