线程计时器是否每次都创建一个新线程?

Does threading timer make a new thread every time?

我最近从这个人那里得到了这个代码here

供参考:

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

我对这段代码的疑问是:它每次运行时都会创建一个新线程吗?如果它确实会影响我的代码(例如:错误或停止?)

谢谢,艾拉。

定时器每次启动时都会创建一个线程。来自 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.

但是它只有一个“实例”运行,因为它会等待您的函数结束,然后再调用自己。所以除非你启动多个 RepeatedTimers...

至于它是否会影响您的代码?除了你需要确保你的代码是线程安全的等等。注意“定时器可以停止(在它的动作开始之前)”,所以调用 stop() 或取消不会在你的函数中途中断。