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

2024-05-08 22:08:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

  • 监视程序确保函数的执行时间不超过x
  • 监视程序确保某些定期执行的函数确实至少每y秒执行一次

我该怎么做?


Tags: 函数程序时间用例看门狗计时器
2条回答

signal.alarm()为程序设置超时,您可以在主循环中调用它,并将其设置为准备容忍的两次中的较大一次:

import signal
while True:
    signal.alarm(10)
    infloop()

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

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秒的时间内完成,请使用:

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

如果您定期执行某些内容,并希望确保至少每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()

相关问题 更多 >