如何将重复计时器安排为 5 分钟间隔。在 00 秒触发,然后在 00 重复。好吧,不是硬实时,但尽可能接近系统滞后。试图避免积聚滞后并接近 00。
语言:Python,操作系统:WinXP x64
系统具有 25ms 分辨率。
任何代码都会有所帮助,tia
我不知道如何比使用threading.Timer更准确。这是“一次性的”,但这只是意味着您以这种方式安排的功能必须立即重新安排自己再安排 300 秒后,第一件事。(您可以通过测量time.time
每次的准确时间并相应地改变下一个调度延迟来增加准确性)。
尝试比较这两个代码示例的时间打印输出:
代码示例 1
import time
delay = 5
while True:
now = time.time()
print time.strftime("%H:%M:%S", time.localtime(now))
# As you will observe, this will take about 2 seconds,
# making the loop iterate every 5 + 2 seconds or so.
## repeat 5000 times
for i in range(5000):
sum(range(10000))
# This will sleep for 5 more seconds
time.sleep(delay)
代码示例 2
import time
delay = 5
while True:
now = time.time()
print time.strftime("%H:%M:%S", time.localtime(now))
# As you will observe, this will take about 2 seconds,
# but the loop will iterate every 5 seconds because code
# execution time was accounted for.
## repeat 5000 times
for i in range(5000):
sum(range(10000))
# This will sleep for as long as it takes to get to the
# next 5-second mark
time.sleep(delay - (time.time() - now))