~/Blog

Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Python: Set Interval

Published on

Updated on

Javascript has a function called setInterval which given a length of time $T$ and a callback function, it will perform that function every $T$ milliseconds. For example, to print “Hello, World!” every 5 seconds:

setInterval(function() {
    console.log("Hello, World!")
}, 5 * 1000)

Wouldn’t it be nice if Python had a similar functionality? Well thanks to right2clicky, there’s a nice and quick way to implement one.

from threading import Timer

class Repeat(Timer):
    def run(self):
        while not self.finished.wait(self.interval):
            self.function(*self.args, **self.kwargs)

Since self.finished.wait only returns True when the Event self.finished is set to true, the thread will keep waiting and calling the function for the set interval time period.

The same post has a usage example:

from time import sleep

t = Repeat(1.0, lambda: print("Hello, World!"))
t.start()
sleep(5)
t.cancel()
Reply via Email Buy me a Coffee
Was this useful? Feel free to share: Hacker News Reddit Twitter