如何使循环与UTC计时器同步并在每隔一分钟执行一次? [英] How to have loop sync with UTC timer and execute at every new minute?

查看:103
本文介绍了如何使循环与UTC计时器同步并在每隔一分钟执行一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

datetime.utcnow()。second 为零时,我希望每分钟执行一次循环。
到目前为止,我有这个

I want to have a loop be executed once every minute when datetime.utcnow().second is zero. So far I have this

while True:
    while datetime.utcnow().second != 0: pass
    do_something()

但问题是我在浪费CPU流程。我会使用 time.sleep(60),但我不知道它将如何与UTC时钟同步,因为 time.sleep(60 )可能会随着时间的流逝而偏离官方UTC时间。

But the problem with this is that I am wasting cpu processes. I would use time.sleep(60), but I don't know how it would sync with the UTC clock, because time.sleep(60) could stray from the official UTC time as time passes.

推荐答案

我能想到的最好方法会一直睡到下一分钟:

Best way I can think of would be to sleep until the next minute:

while True:
    sleeptime = 60 - datetime.utcnow().second
    time.sleep(sleeptime)
    ...

如果需要准确地说:

while True:
    t = datetime.utcnow()
    sleeptime = 60 - (t.second + t.microsecond/1000000.0)
    time.sleep(sleeptime)
    ...

此时间完全睡到下一分钟所需的时间,精确到亚秒。

This sleeps for exactly the amount of time necessary to reach the next minute, with subsecond precision.

已编辑修复分钟翻转错误。

这篇关于如何使循环与UTC计时器同步并在每隔一分钟执行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆