0
我從這個webaddress http://code.activestate.com/recipes/577407-resettable-timer-class-a-little-enhancement-from-p/復位定時器,直至取消
複製的代碼創建一個復位定時器,它工作得很好,但一旦完成結束。我想再次開始,但我是新的,並不能解決如何做到這一點。
在run()函數的行之後的底部我累了創造自己的新實例:
print "Time: %s - timer finished!" % time.asctime()
但蟒蛇似乎並不喜歡它。
由渦雅各創建拷貝粘貼代碼是這樣的:
from threading import Thread, Event, Timer
import time
def TimerReset(*args, **kwargs):
""" Global function for Timer """
return _TimerReset(*args, **kwargs)
class _TimerReset(Thread):
"""Call a function after a specified number of seconds:
t = TimerReset(30.0, f, args=[], kwargs={})
t.start()
t.cancel() # stop the timer's action if it's still waiting
"""
def __init__(self, interval, function, args=[], kwargs={}):
Thread.__init__(self)
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
self.resetted = True
def cancel(self):
"""Stop the timer if it hasn't finished yet"""
self.finished.set()
def run(self):
print "Time: %s - timer running..." % time.asctime()
while self.resetted:
print "Time: %s - timer waiting for timeout in %.2f..." % (time.asctime(), self.interval)
self.resetted = False
self.finished.wait(self.interval)
if not self.finished.isSet():
self.function(*self.args, **self.kwargs)
self.finished.set()
print "Time: %s - timer finished!" % time.asctime()
def reset(self, interval=None):
""" Reset the timer """
if interval:
print "Time: %s - timer resetting to %.2f..." % (time.asctime(), interval)
self.interval = interval
else:
print "Time: %s - timer resetting..." % time.asctime()
self.resetted = True
self.finished.set()
self.finished.clear()
我用跑我定時器:
tim = TimerReset(10, AddBlank)
tim.start()
功能AddBlank做一些事情,但我想計時器再次調用但只有在它結束後。真的很感謝幫助,這一點,我知道複製代碼,而不理解它是不好的做法,但我真的只是想簡單的復位定時器可重複調用一個函數,除非重置,這幾乎做到這一點。
這很好,唉,當卸載/終止程序時python會崩潰。 – Zac 2013-03-27 15:40:17
希望我能幫上更多。我很確定問題在於在卸載時正確地結束線程,但是我看到(在聊天中)你無法讓它工作。如果您添加更多詳細信息(或者提出有關該部分的新問題),我或其他人可能會提供幫助。 :3 – Poik 2013-03-27 20:23:53