In python, I have code that needs to be triggered and the top of every minute. I have a while loop. What is the best why to watch the time and when a new minute start then execute?
Thanks
while True:
if TOP_OF_MIN:
run_code()
In python, I have code that needs to be triggered and the top of every minute. I have a while loop. What is the best why to watch the time and when a new minute start then execute?
Thanks
while True:
if TOP_OF_MIN:
run_code()
A minute is a looooong time in a program. Find out how many seconds are left in this minute, sleep for this long, then sleep 60 seconds per cycle-- or just keep checking the seconds, which guards against gradual drift.
while True:
now = time.localtime().tm_sec
time.sleep(60 - now) # `now` is between 0 and 59, so we always sleep
print("tick")
If you need better than second accuracy, use one of the functions that return the number of seconds as a fraction (e.g., time.time()
)