How to implement a watchdog timer in Python?

大城市里の小女人 提交于 2019-11-28 06:06:05
Sergiy Byelozyorov

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