python中计时器的一点误解
有人能告诉我如何在我的代码中多次使用python中的此类计时器吗python中计时器的一点误解,python,timer,Python,Timer,有人能告诉我如何在我的代码中多次使用python中的此类计时器吗 import MOD class timer: def __init__(self, seconds): self.start(seconds) def start(self, seconds): self.startTime = MOD.secCounter() self.expirationTime = self.startTime + seconds
import MOD
class timer:
def __init__(self, seconds):
self.start(seconds)
def start(self, seconds):
self.startTime = MOD.secCounter()
self.expirationTime = self.startTime + seconds
if seconds != 0:
self.running = 1
self.expired = 0
else:
self.running = 0
self.expired = 0
def stop(self):
self.running = 0
self.expired = 0
def isexpired(self):
if self.running == 1:
timeNow = MOD.secCounter()
if timeNow > self.expirationTime:
self.running = 0
self.expired = 1
else:
self.expired = 0
return self.expired
def isrunning(self):
if self.running == 1:
timeNow = MOD.secCounter()
if timeNow > self.expirationTime:
self.running = 0
self.expired = 1
else:
self.expired = 0
return self.running
def change(self, seconds):
self.expirationTime = self.startTime + seconds
def count(self):
if self.running == 1:
timeNow = MOD.secCounter()
return (timeNow - self.startTime)
else:
return -1
他们写道:
下面是一个关于如何使用此类的简单示例:
import timers
timerA = timers.timer(0)
timerA.start(15)
while 1:
if timerA.isexpired():
print 'timerA expired'
break
但我不知道如何在代码中多次使用它,因为我需要在代码中使用多个计时器
我应该写信吗
timerB = timers.timer(1)
timerB.start(1800)
while 1:
if timerB.isexpired():
print 'timerA expired'
break
任何帮助,请关闭-timers.timer的参数是计时器开始计时的秒数。但每次调用timers.timer(),都会得到一个新的计时器实例 因此,您的代码看起来更像:
timerB = timers.timer(1800)
while 1:
if timerB.isexpired():
print 'timerA expired'
break
只是这有误导性——timerA和timerB是独立的计时器,所以timerB.isexpired()
不会告诉您任何关于timerA的信息。也许你的意思是读“timerB过期”
我还建议不要如此快速地轮询
timerB.isexpired()。每次检查后可能会睡上一秒钟?你的意思是我不应该写timerB.start(1800)当我写timerB=timer.timer(1800)时,你不需要这样做,因为计时器构造函数调用timer.start(),参数是你传递的。如果要重置计时器,则可以显式调用start()。另外,如果这个答案对你有效,如果你明天能接受它就好了,因为我今天已经筋疲力尽了。