Tuesday, 12 April 2011

Remember to just read the code

The problem that I had was that I needed a repeating Timer object in python. I googled, but the answers that I found didn't sit right, and then I remembered that I could just read the code for the threading module and see how the Timer object was implemented, then just use that. Below is the code I came up with.

But the moral of the story is that having the source code for your language's core libaries around is a good thing.

class RepeatingTimer(threading.Thread):
    """Call a function after a specified number of seconds, it will then repeat again after the specified number of seconds
       Note: If the function provided takes time to execute, this time is NOT taken from the next wait period

    t = RepeatingTimer(30.0, f, args=[], kwargs={})
    t.cancel() # stop the timer's actions

    def __init__(self, interval, function, args=[], kwargs={}):
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = threading.Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet"""

    def run(self):
        while not self.finished.is_set():
            if not self.finished.is_set():  #In case someone has canceled while waiting
                self.function(*self.args, **self.kwargs)