How to implement a watchdog timer in Python?
我想在Python中实现一个简单的看门狗计时器,它有两个用例:
- 看门狗确保函数的执行时间不超过
x 秒。 - 看门狗确保某些定期执行的函数确实至少每
y 秒执行一次。
我该怎么做?
只需发布我自己的解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from threading import Timer class Watchdog: def __init__(self, timeout, userHandler=None): # timeout in seconds self.timeout = timeout self.handler = userHandler if userHandler is not None else self.defaultHandler self.timer = Timer(self.timeout, self.handler) self.timer.start() def reset(self): self.timer.cancel() self.timer = Timer(self.timeout, self.handler) self.timer.start() def stop(self): self.timer.cancel() def defaultHandler(self): raise self |
如果要确保函数在不到
1 2 3 4 5 6 | watchdog = Watchdog(x) try: # do something that might take too long except Watchdog: # handle watchdog error watchdog.stop() |
用法:如果您经常执行某项操作,并且希望确保至少每隔
1 2 3 4 5 6 7 8 9 10 11 | import sys def myHandler(): print"Whoa! Watchdog expired. Holy heavens!" sys.exit() watchdog = Watchdog(y, myHandler) def doSomethingRegularly(): # make sure you do not return in here or call watchdog.reset() before returning watchdog.reset() |
1 2 3 4 | import signal while True: signal.alarm(10) infloop() |