当 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计时器同步并在每隔一分钟执行一次?
发布评论