I would like to implement a simple watchdog timer in Python with two use cases:
- Watchdog ensures that a function doesn't execute longer than
x
seconds
- Watchdog ensures that certain regularly executed function does indeed execute at least every
y
seconds
How do I do that?
Just publishing my own solution to this:
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
Usage if you want to make sure function finishes in less than x
seconds:
watchdog = Watchdog(x)
try:
# do something that might take too long
except Watchdog:
# handle watchdog error
watchdog.stop()
Usage if you regularly execute something and want to make sure it is executed at least every y
seconds:
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()
signal.alarm()
sets a timeout for your program, and you can call it in your main loop, and set it to the greater of the two times you are prepared to tolerate:
import signal
while True:
signal.alarm(10)
infloop()