定时器和线程有什么区别? Python,穿线
What's the difference between Timer and Thread? Python, threading
threading.Timer
和threading.Thread
有什么区别?
当我使用 Timer 函数时,它会在单独的线程中延迟启动目标命令。
当我使用 Thread 函数时,它在单独的线程中启动带有 args 的目标命令。
我想是一样的吧?
值得一看实现。
# _Timer is thinly wrapped by Timer; excluding that wrapper for terseness
class _Timer(Thread):
"""Call a function after a specified number of seconds:
t = Timer(30.0, f, args=[], kwargs={})
t.start()
t.cancel() # stop the timer's action if it's still waiting
"""
def __init__(self, interval, function, args=[], kwargs={}):
Thread.__init__(self)
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
def cancel(self):
"""Stop the timer if it hasn't finished yet"""
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()
因此,是的,Timer 只是 Thread 的一个实例,它在给定延迟后调用您的函数,使用 Event 机制进行高效调度并提供 cancel()
可靠地阻止该函数如果延迟尚未到期,则根本不会被调用。
正如我们在上面看到的,Thread
是完成繁重工作的实现,Timer
是添加额外功能的助手(在前端延迟);如果 Thread
不存在,Timer(0, func)
将不起作用。
A Thread
是一个对象比 仅 能够覆盖要调用的函数,而无需该函数访问实例变量 -看看 Timer
本身,以及它如何使用该功能来添加和尊重 cancel()
。如果不对 _Timer
进行子类化,则不能在 Timer
之上执行此操作,这(顾名思义)是一个实现细节,未承诺在未来的版本中保持稳定。
因此,Timer()
比 Thread()
有更多的活动部件并且灵活性较低——这两者都是软件工程中的先天缺点——但对于特定的中等常见用例来说很方便.为什么一个不同时提供两者?
您已经解释了其中的区别。 Thread
是线程,Timer
是至少延迟指定时间执行的线程。
https://docs.python.org/2/library/threading.html#timer-objects
threading.Timer
和threading.Thread
有什么区别?
当我使用 Timer 函数时,它会在单独的线程中延迟启动目标命令。
当我使用 Thread 函数时,它在单独的线程中启动带有 args 的目标命令。
我想是一样的吧?
值得一看实现。
# _Timer is thinly wrapped by Timer; excluding that wrapper for terseness
class _Timer(Thread):
"""Call a function after a specified number of seconds:
t = Timer(30.0, f, args=[], kwargs={})
t.start()
t.cancel() # stop the timer's action if it's still waiting
"""
def __init__(self, interval, function, args=[], kwargs={}):
Thread.__init__(self)
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
def cancel(self):
"""Stop the timer if it hasn't finished yet"""
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()
因此,是的,Timer 只是 Thread 的一个实例,它在给定延迟后调用您的函数,使用 Event 机制进行高效调度并提供 cancel()
可靠地阻止该函数如果延迟尚未到期,则根本不会被调用。
正如我们在上面看到的,Thread
是完成繁重工作的实现,Timer
是添加额外功能的助手(在前端延迟);如果 Thread
不存在,Timer(0, func)
将不起作用。
A Thread
是一个对象比 仅 能够覆盖要调用的函数,而无需该函数访问实例变量 -看看 Timer
本身,以及它如何使用该功能来添加和尊重 cancel()
。如果不对 _Timer
进行子类化,则不能在 Timer
之上执行此操作,这(顾名思义)是一个实现细节,未承诺在未来的版本中保持稳定。
因此,Timer()
比 Thread()
有更多的活动部件并且灵活性较低——这两者都是软件工程中的先天缺点——但对于特定的中等常见用例来说很方便.为什么一个不同时提供两者?
您已经解释了其中的区别。 Thread
是线程,Timer
是至少延迟指定时间执行的线程。
https://docs.python.org/2/library/threading.html#timer-objects