我正在尝试创建一个可以的类 1.保持活力 2.定期监视自己并做一些事情来纠正自己(即数据停止进入,重生自我)
我目前正在这样做:
class SelfMonitorClass(object):
exit_flag = False
def __init__(self):
self.flush_timer = 10 # in seconds, how often we should check ourselves!
self.perpetual_runner()
def do_actions(self):
# do stuff! add things together
# check that temperature ect is in some range
print('I AM DOING AN ACTION!')
def perpetual_runner(self):
self.do_actions() # actually go do something!!
if self.exit_flag == False: # POISON PILL check
athread = threading.Timer(self.flush_timer, self.perpetual_runner);
athread.daemon = True
athread.start()
def kill(self)
self.exit_flag = True
if __name__ == '__main__':
aclass = SelfMonitorClass()
print('Main thread exits!')
>>>> 'I AM DOING SOMETHING'
>>>> 'Main thread exits!'
>>>> 'I AM DOING SOMETHING' # repeat every 10 seconds, while console is still up. Regardless of the fact '__main__' is done.
这种做事方式是个好主意吗?我应该以另一种方式实现这样的事情吗?生命继续存在的属性对我来说非常重要。
此外,如果有可以为我处理此类事情的包裹会很棒!
杀死这个程序是相当烦人的(找到进程,sigTERM / sigKILL。这样的东西),但这不是这里的主要问题。只是保持线程活着并定期检查内部状态并做某事。