python 函数未使用 threading.timer 每 n 秒调用一次

python function is not calling for every n seconds using threading.timer

Class A:

  def get_data(self,arg1):

    ........

  def test(self):

    self.timer = threading.Timer(1,self.get_data, args=(arg1,))

    self.timer.start()
    ......

    self.timer.cancel()

在尝试调用 get_data() 时,每一秒都没有调用。

代码的其他部分正在执行。没有语法或缩进错误

观察到。请让我知道这里遗漏的东西。

那是因为 threading.Timer 只调用一次目标函数(如此处记录:https://docs.python.org/2/library/threading.html#timer-objects)。

您真正想要做的是创建一个 threading.Thread 实例,其目标是一个无限循环调用 get_data 并休眠 1 秒的函数。

并且您希望在达到特定条件时停止该循环——例如将 running 标志设置为 False。这样,您可以 停止 循环,一旦您不再需要它 运行.