13

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.

Steven
  • 177
  • 1
  • 1
  • 8

1 Answers1

39

use a thread

import threading

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

hello_world()
danidee
  • 9,298
  • 2
  • 35
  • 55
  • 1
    It's a decent answer, but it introduces a drift (always minimally longer than the interval), [this answer](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python/25251804#25251804) is more accurate over time: – smoothware Apr 16 '19 at 21:26