定时器的暂停/恢复功能 [英] Pause/Resume functions for timer
本文介绍了定时器的暂停/恢复功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用一个可以暂停和恢复的计时器.据我所知,Python 中只有一个计时器包含在 threading
包中,但我无法暂停或恢复它,只能取消它.
I need to use a timer which can be paused and resumed. As far as I know there is only one timer in Python which is contained in the threading
package, but I cannot pause or resume it, only cancel it.
这是在 Python 中使用计时器的标准代码:
This is a standard code to use the timer in Python:
from threading import Timer
import time
def timeout():
print "Game over"
t = Timer(20 * 60, timeout)
t.start()
那么我应该怎么做才能用这个定时器实现暂停/恢复功能?
So what should I do to realize pause/resume functions with this timer?
推荐答案
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()
你的作业:
- 继承?
- 例外?检查?
- 比可恢复计时器更好的东西
这篇关于定时器的暂停/恢复功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文