Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have loop sync with UTC timer and execute at every new minute?

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()

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.

like image 972
user299648 Avatar asked Aug 25 '12 03:08

user299648


1 Answers

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

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

If you want to be really precise:

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.

EDITED to fix minute rollover bug.

like image 132
nneonneo Avatar answered Sep 30 '22 07:09

nneonneo