1

I've been using the code from another solution which works well but I would like to add some functionality. The following class creates a threaded timer that starts immediately after the start method is called. I would like the timer to wait some length of time before starting the repeating timer.

import time
from threading import Timer

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

def hello():
    print('hello')

t = RepeatTimer(2, hello)
t.start()

This will print "hello" every two seconds until t.cancel() is called.

I would like for the timer to wait N number of seconds before starting the repeating timer. I tried modifying the class to take an additional parameter, but it does not work.

class RepeatTimer(Timer):
    def __init__(self, initial_delay):
        super().__init__()
        self.initial_delay = initial_delay
    
    def run(self):
        time.sleep(initial_delay)
        while not self.finished.wait(self.interval):
            self.function(*self.args, **self.kwargs)

t = RepeatTimer(2, hello, 5)

With the error??

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: __init__() takes 2 positional arguments but 4 were given

I've also tried adding all of the Timer arguments to the __init__ method but that doesn't help.

class RepeatTimer(Timer):
    def __init__(self, interval, function, initial_delay):
        super().__init__()
        self.interval = interval
        self.function = function
        self.initial_delay = initial_delay
    
    def run(self):
        time.sleep(initial_delay)
        while not self.finished.wait(self.interval):
            self.function(*self.args, **self.kwargs)

t = RepeatTimer(2, hello, 5)
 TypeError: __init__() missing 2 required positional arguments: 'interval' and 'function'

I think I'm struggling with creating a subclass of Timer. Suggestions welcomed?

TheEagle
  • 5,808
  • 3
  • 11
  • 39
Geoff D
  • 369
  • 4
  • 14
  • your error is because in your RepeatTimer(2, hello, 5), that is more than the arguement requestion for __init__(self, initial_delay): which is one. – MEdwin May 02 '19 at 16:02
  • 2
    You are getting close with your second example: change `super().__init__()` with `super().__init__(interval, function)` – Jacques Gaudin May 02 '19 at 17:27

1 Answers1

1

Thanks, Jacques Gaudin. I had the super() syntax wrong.

class RepeatTimer(Timer):
    def __init__(self, interval, function, initial_delay):
        super().__init__(interval, function)
        self.initial_delay = initial_delay

    def run(self):
        time.sleep(initial_delay)
        while not self.finished.wait(self.interval):
            self.function(*self.args, **self.kwargs)
Geoff D
  • 369
  • 4
  • 14