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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With