<p>只是发布我自己的解决方案:</p>
<pre><code>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
</code></pre>
<p>如果要确保函数在不到<code>x</code>秒的时间内完成,请使用:</p>
<pre><code>watchdog = Watchdog(x)
try:
# do something that might take too long
except Watchdog:
# handle watchdog error
watchdog.stop()
</code></pre>
<p>如果您定期执行某些内容,并希望确保至少每<code>y</code>秒执行一次,请使用:</p>
<pre><code>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()
</code></pre>