如何在Python中实现watchdog定时器?

How to implement a watchdog timer in Python?

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

  • 看门狗确保函数的执行时间不超过x秒。
  • 看门狗确保某些定期执行的函数确实至少每y秒执行一次。

我该怎么做?


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

如果要确保函数在不到x秒内完成,请使用:

1
2
3
4
5
6
watchdog = Watchdog(x)
try:
  # do something that might take too long
except Watchdog:
  # handle watchdog error
watchdog.stop()

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

1
2
3
4
5
6
7
8
9
10
11
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()为您的程序设置了一个超时,您可以在主循环中调用它,并将其设置为您准备容忍的两次中的较大一次:

1
2
3
4
import signal
while True:
    signal.alarm(10)
    infloop()