threading.Timer – repeat function every ‘n’ seconds

The best way is to start the timer thread once. Inside your timer thread you’d code the following class MyThread(Thread): def __init__(self, event): Thread.__init__(self) self.stopped = event def run(self): while not self.stopped.wait(0.5): print(“my thread”) # call a function In the code that started the timer, you can then set the stopped event to stop the … Read more

Time-Limited Input? [duplicate]

If it is acceptable to block the main thread when user haven’t provided an answer: from threading import Timer timeout = 10 t = Timer(timeout, print, [‘Sorry, times up’]) t.start() prompt = “You have %d seconds to choose the correct answer…\n” % timeout answer = input(prompt) t.cancel() Otherwise, you could use @Alex Martelli’s answer (modified … Read more