I would like to implement a simple watchdog timer in Python with two use cases:
x
secondsy
secondsHow do I do that?
watchdog is an open-source python API library that is a cross-platform API to monitor file system events. You can specify a folder or a directory to watchdog observer, which keeps monitoring the folder for any changes like file creation, modification, deletion, or moving of files from one folder to another.
A timer in Python is a time-tracking program. Python developers can create timers with the help of Python's time modules. There are two basic types of timers: timers that count up and those that count down.
A watchdog timer (WDT) is a timer that monitors microcontroller (MCU) programs to see if they are out of control or have stopped operating. It acts as a “watchdog” watching over MCU operation. A microcontroller (MCU) is a compact processor for controlling electronic devices.
A watchdog timer (WDT) is a device or electronic card that performs a specific operation after a certain period of time if something goes wrong with an electronic system and the system does not recover on its own.
Just publishing my own solution to this:
from threading import Timer
class Watchdog(Exception):
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With