如何在Python中实现看门狗定时器?

Ser*_*rov 9 python watchdog

我想在Python中实现一个简单的看门狗定时器,有两个用例:

  • Watchdog确保函数的执行时间不超过x秒
  • 看门狗确保某些经常执行的功能确实执行至少每y秒

我怎么做?

Ser*_*rov 11

只需发布我自己的解决方案:

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
Run Code Online (Sandbox Code Playgroud)

用法如果要确保函数在少于x几秒内完成:

watchdog = Watchdog(x)
try:
  # do something that might take too long
except Watchdog:
  # handle watchdog error
watchdog.stop()
Run Code Online (Sandbox Code Playgroud)

用法,如果您经常执行某些操作并希望确保至少每秒执行一次y:

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()
Run Code Online (Sandbox Code Playgroud)

  • 这个“Watchdog”在单独的线程(“Timer”线程)中引发“Exception”(本身),因此使用示例中的“try”/“ except”是无用的。“看门狗”也不会中断长时间操作,这正是看门狗的重点。 (7认同)
  • 我认为`__init__`函数和`reset`函数需要调用[`self.timer.start()`](http://docs.python.org/2/library/threading.html#timer-objects). (4认同)