简体   繁体   中英

Repeat a threaded timer with a start delay

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 "", line 1, in 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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM