gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:52:14 28 4
gpt4 key购买 nike

我想用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com