[英]How to implement a watchdog timer in Python?
我想用兩個用例在 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()
signal.alarm()
為您的程序設置超時,您可以在主循環中調用它,並將其設置為您准備容忍的兩次時間中的較大者:
import signal
while True:
signal.alarm(10)
infloop()
這是我在我的應用程序中使用的 wdt,沒有課。 它沒有辦法阻止它:
from threading import Event, Thread
def wdt(time, callback):
# a reset flag
reset_e = Event()
# a function to reset the wdt
def reset(): reset_e.set()
# the function to run in a differen thread
def checker():
# check if reset flag is set.
# wait for specified time to give chance to reset.
while reset_e.wait(time):
# it was set in time. clear and wait again
reset_e.clear()
# time run out.
callback()
# the event is not set by default. Set it
reset()
# create and start the wdt
t = Thread(target=checker)
t.start()
# return the resetter
return reset
# The callback to run if wdt is not reset
def bark():
print('woof')
# Test
import time
reset = wdt(1.0, bark)
time.sleep(0.9)
reset()
time.sleep(2.0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.