使用Python: 每小时x:00重复的区间

1 投票
2 回答
827 浏览
提问于 2025-04-16 03:12

我想设置一个每5分钟重复的定时器。它应该在每个整点的00秒触发,然后再重复。虽然实时性不容易做到,但我希望尽量减少系统延迟,避免延迟累积,尽量接近00秒。

编程语言:Python,操作系统:WinXP x64

系统的时间精度是25毫秒。

任何代码示例都很有帮助,谢谢!

2 个回答

0

试着对比一下这两个代码示例的时间输出:

代码示例 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))
2

我不知道怎么做得比用 threading.Timer 更准确。这个方法是“单次触发”,但这只是意味着你安排的那个函数必须立刻自己重新安排在300秒后再执行一次,作为第一步。(你可以通过每次用 time.time 测量确切的时间来增加准确性,然后相应地调整下次的延迟时间)。

撰写回答