我有这个非阻塞计时器:
import time
class Timer:
def __init__(self):
self.status = 0
def update(self, data, tv):
self.target = time.time() + data
self.status = 1
def set_status(self, state):
self.status = state
def get_status(self, tv):
return self.status
def get_left(self, tv):
return int(self.target-time.time())
当我想在主循环中使用计时器时,它非常适合:例如:
t = Timer()
while 1:
#If timer is not active.
if t.get_status() == 0:
# Do some checks.
# Start timer with 60 seconds.
t.update(60)
#If timer is active.
if t.get_status() == 1:
print "%s seconds left." % str(t.get_left())
if t.get_left() <= 0:
t.set_status(0)
# Timer is done do some stuff.
time.sleep(1)
我希望能够在不执行线程的情况下处理多个计时器。
答案 0 :(得分:0)
这是我自己的解决方案,如果有人有更好的想法,请告诉我。
import time
class Timer:
def __init__(self):
self.status = {}
self.target = {}
def update(self, tv, data):
self.target[tv] = time.time() + data
self.status[tv] = 1
def set_status(self, tv, state):
self.status[tv] = state
def get_status(self, tv):
return self.status[tv]
def get_left(self, tv):
return int(self.target[tv]-time.time())
t = Timer()
t.set_status('A', 0)
t.set_status('B', 0)
while 1:
# Timer A checks
if t.get_status('A') == 0:
print "Timer A checks."
# Start timer with 60 seconds.
t.update('A', 60)
if t.get_status('A') == 1:
print "A has %s seconds left." % str(t.get_left('A'))
if t.get_left('A') <= 0:
t.set_status('A', 0)
print "Timer A done."
# Timer B checks
if t.get_status('B') == 0:
print "Timer B checks."
# Start timer with 30 seconds
t.update('B', 30)
if t.get_status('B') == 1:
print "B has %s seconds left." % str(t.get_left('B'))
if t.get_left('B') <= 0:
t.set_status('B', 0)
print "Timer B done."
time.sleep(1)