如何使循环与UTC计时器同步并在每隔一分钟执行一次?

编程入门 行业动态 更新时间:2024-10-22 02:57:20
本文介绍了如何使循环与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计时器同步并在每隔一分钟执行一次?

本文发布于:2023-11-24 09:04:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   并在   每隔   UTC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!