簡體   English   中英

如何在 Python 中實現看門狗定時器?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM