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

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

  • 我怎么做?

    最佳答案

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

    from threading import Timer
    
    class Watchdog(Exception):
        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()
    

    关于python - 如何在Python中实现看门狗计时器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16148735/

    10-12 22:03