2014-09-28 190 views
2

我需要使用一個可以暫停和恢復的定時器。據我所知Python中只有一個包含在threading包中的計時器,但我無法暫停或恢復它,只能取消它。定時器的暫停/恢復功能

這是使用Python中的計時器標準代碼:

from threading import Timer 
import time 

def timeout(): 
    print "Game over" 

t = Timer(20 * 60, timeout) 
t.start() 

所以,我應該怎麼做才能實現暫停/恢復功能,這個計時器?

回答

3
import threading, time 

class ResumableTimer: 
    def __init__(self, timeout, callback): 
     self.timeout = timeout 
     self.callback = callback 
     self.timer = threading.Timer(timeout, callback) 
     self.startTime = time.time() 

    def start(self): 
     self.timer.start() 

    def pause(self): 
     self.timer.cancel() 
     self.pauseTime = time.time() 

    def resume(self): 
     self.timer = threading.Timer(
      self.timeout - (self.pauseTime - self.startTime), 
      self.callback) 

     self.timer.start() 

功課:

  • 繼承?
  • 例外?檢查?
  • 東西比可恢復定時器
+0

非常感謝你更好! – 2014-09-28 21:10:37

+0

試試吧,'t = ResumableTimer(5,someFunction); t.start(); t.pause(); t.resume()'並將我的問題標記爲正確,如果它有效。 – 2014-09-28 21:12:25

1

final類釋放

from threading import Timer 
import time 

class RenewableTimer(): 

    def __init__(self, timeout, callback): 
     self.timeout = timeout 
     self.callback = callback 
     self.timer = Timer(timeout, callback) 

    def cancel(self): 
     self.timer.cancel() 

    def start(self): 
     self.start_time = time.time() 
     self.timer.start() 

    def pause(self): 
     self.cancel_time = time.time() 
     self.timer.cancel() 
     return self.get_actual_time() 

    def resume(self): 
     self.timeout = self.get_actual_time() 
     self.timer = Timer(self.timeout, self.callback) 
     self.start_time = time.time() 
     self.timer.start() 

    def get_actual_time (self): 
     return self.timeout - (self.cancel_time - self.start_time)