我有一个工作单位我希望每N秒发生一次.如果我使用简单化
minute = 60
while True:
doSomeWork()
time.sleep(minute)
取决于doSomeWork()花费的时间,实际循环周期将是一分钟加上那个时间.如果doSomeWork()所花费的时间不是确定性的,则工作周期更加难以预测.
我想做的就是这样
minute = 60
start = time.process_time() #? i can imagine using this, but maybe there's something better?
while True:
doSomeWork()
start += minute
sleep_until(start) #? this is the function I'm in search of
(我正在使用python 3.3)
更新:
在Linux / OSX上,我可以使用itimer from signal来做我正在寻找的东西:
import signal
import datetime
def tick(_, __):
# doSomeWork()
print(datetime.datetime.now())
signal.setitimer(signal.ITIMER_REAL, 60, 60)
signal.signal(signal.SIGALRM, tick)
while True:
signal.pause()
看起来为python3.4开发的郁金香东西也会让这很容易.
解决方法:
sleep_until(timestamp)基本上是time.sleep(timestamp – time.time()).
你的代码实际上是很好的(确保你没有通过负面时间睡觉仍然是一个好主意):
import time
minute = 60
next_time = time.time()
while True:
doSomeWork()
next_time += minute
sleep_time = next_time - time.time()
if sleep_time > 0:
time.sleep(sleep_time)
我个人会制作一个60秒间隔时间戳的发生器并使用它:
import time
import itertools
minute = 60
for next_time in itertools.count(time.time() + minute, minute):
doSomeWork()
sleep_time = next_time - time.time()
if sleep_time > 0:
time.sleep(sleep_time)
标签:python,python-3-x