0

I recently got this code from this person here

For reference:

from threading import Timer

class RepeatedTimer(object):
    def __init__(self, interval, function, *args, **kwargs):
        self._timer = None
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.is_running = False
        self.start()

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

My question about this code is: Does it make a new thread every time it runs? And if it does can it affect my code in anyway (e.g: Error or stop?)

Thanks, Ira.

petezurich
  • 9,280
  • 9
  • 43
  • 57

1 Answers1

0

Timer makes a thread every time it is started. From the docs:

This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads.

Timers are started, as with threads, by calling their start() method. The timer can be stopped (before its action has begun) by calling the cancel() method.

But there is only ever one "instance" of it running because it waits for your function to end before calling itself again. So unless you start multiple RepeatedTimers...

As to whether it can affect your code? Apart from you needing to make sure your code is threadsafe etc. note that the "timer can be stopped (before its action has begun)", so calling stop() or cancelling won't break halfway through your function.

Community
  • 1
  • 1
Will
  • 1,532
  • 10
  • 22