暂停/恢复计时器功能

时间:2014-09-28 20:35:53

标签: python python-2.7

我需要使用一个可以暂停和恢复的计时器。据我所知,Python中只有一个计时器包含在threading包中,但我不能暂停或恢复它,只能取消它。

这是在Python中使用计时器的标准代码:

from threading import Timer
import time

def timeout():
     print "Game over"

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

那么我应该怎么做才能用这个计时器实现暂停/恢复功能呢?

2 个答案:

答案 0 :(得分: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()

你的作业:

  • 继承?
  • 异常?检查?
  • 比可恢复的计时器更好的东西

答案 1 :(得分:1)

最终课程发布

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)