我用它来每小时导致60个事件,而大多数事件在整分钟后的相同秒数内发生:
import math
import time
import random
TICK = 60 # one minute tick size
TICK_TIMING = 59 # execute on 59th second of the tick
TICK_MINIMUM = 30 # minimum catch up tick size when lagging
def set_timing():
now = time.time()
elapsed = now - info['begin']
minutes = math.floor(elapsed/TICK)
tick_elapsed = now - info['completion_time']
if (info['tick']+1) > minutes:
wait = max(0,(TICK_TIMING-(time.time() % TICK)))
print ('standard wait: %.2f' % wait)
time.sleep(wait)
elif tick_elapsed < TICK_MINIMUM:
wait = TICK_MINIMUM-tick_elapsed
print ('minimum wait: %.2f' % wait)
time.sleep(wait)
else:
print ('skip set_timing(); no wait')
drift = ((time.time() - info['begin']) - info['tick']*TICK -
TICK_TIMING + info['begin']%TICK)
print ('drift: %.6f' % drift)
info['tick'] = 0
info['begin'] = time.time()
info['completion_time'] = info['begin'] - TICK
while 1:
set_timing()
print('hello world')
#random real world event
time.sleep(random.random()*TICK_MINIMUM)
info['tick'] += 1
info['completion_time'] = time.time()
根据实际情况,您可能会发现一些问题:
60,60,62,58,60,60,120,30,30,60,60,60,60,60...etc.
但在60分钟结束时,您将有60个滴答声;并且大多数会以您希望的分钟数正确偏移。
在我的系统上,我得到的典型漂移小于<1/20秒,直到需要校正为止。
这种方法的优点是可以解决时钟漂移问题。如果您正在做一些事情,例如每滴答声追加一项,而您希望每小时追加60项,则可能会引起问题。不能考虑漂移会导致诸如移动平均线之类的次要指示,以至于认为数据太过深了而导致输出错误。