How to implement a watchdog timer in Python?

江枫思渺然 提交于 2019-11-27 01:11:39

问题


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?


回答1:


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()



回答2:


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()


来源:https://stackoverflow.com/questions/16148735/how-to-implement-a-watchdog-timer-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!