gpt4 book ai didi

python - python中定时器的一些误解

转载 作者:行者123 更新时间:2023-12-01 06:18:25 25 4
gpt4 key购买 nike

有人可以告诉我如何在我的代码中多次使用 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
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()。每次检查后也许可以睡一会儿?

关于python - python中定时器的一些误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1943182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com