2

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()
Tampa
  • 75,446
  • 119
  • 278
  • 425
  • 1
    Better use a scheduler such as `cron` for Unix'es or `at` for Windows'es. – Selcuk Mar 17 '16 at 13:31
  • not every 60 seconds. At the top of the minute and no I dont need a cron. Thanks – Tampa Mar 17 '16 at 13:40
  • Why the close votes? The question is clear, specific and not a duplicate of the linked question (The scheduler might be one approach to doing things on the whole minute, but schedulers can delay for up to a minute... so I wouldn't recommend doing it this way.) – alexis Mar 17 '16 at 13:53

1 Answers1

2

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

alexis
  • 48,685
  • 16
  • 101
  • 161