重复启动延迟的线程计时器

时间:2019-05-02 15:56:44

标签: python subclass

我一直在使用另一个solution的代码,效果很好,但是我想添加一些功能。下列类创建线程计时器,该计时器在调用start方法后立即启动。我希望计时器在启动重复计时器之前要等待一段时间。

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()

这将每两秒打印一次“ hello”,直到调用t.cancel()

我希望计时器在启动重复计时器之前等待N秒。我尝试修改该类以采用其他参数,但这不起作用。

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)

出现错误?

  

回溯(最近一次通话最后一次):文件“”,第1行,在    TypeError: init ()接受2个位置参数,但其中4个是   给

我也尝试将所有Timer参数添加到__init__方法中,但这无济于事。

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 ()缺少2个必需的位置参数:   “间隔”和“功能”

我认为我正在努力创建Timer的子类。欢迎提出建议?

1 个答案:

答案 0 :(得分:0)

谢谢Jacques Gaudin。我的super()语法错误。

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)
相关问题