How to repeat a function every N minutes?

39,890

use a thread

import threading

def hello_world():
    threading.Timer(60.0, hello_world).start() # called every minute
    print("Hello, World!")

hello_world()
Share:
39,890
Steven
Author by

Steven

Updated on July 09, 2022

Comments

  • Steven
    Steven almost 2 years

    In my python script I want to repeat a function every N minutes, and, of course, the main thread has to keep working as well. In the main thread I have this:

    # something
    # ......
    while True:
      # something else
      sleep(1)
    

    So how can I create a function (I guess, in another thread) which executes every N minutes? Should I use a timer, or Even, or just a Thread? I'm a bit confused.

  • smoothware
    smoothware about 5 years
    It's a decent answer, but it introduces a drift (always minimally longer than the interval), this answer is more accurate over time: