gpt4 book ai didi

python - threading.Timer 是否在单独的线程中打开函数?

转载 作者:行者123 更新时间:2023-12-01 04:27:26 24 4
gpt4 key购买 nike

当我使用 threading.Timer 调用函数时,如下所示:

threading.Timer(LOOP_TIME,self.broadCast).start()

broadCast 是否在单独的线程中运行?或者只是在同一个线程中?我正在使用 threading.Timer,这样我就可以每隔这么长时间的时间间隔调用一个函数。我不希望在主线程之外调用broadCast 函数。

最佳答案

是的。您可以查看Python threading.py源代码:

def Timer(*args, **kwargs):
"""Factory function to create a Timer object.

Timers 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

"""
return _Timer(*args, **kwargs)

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

Source code available in Python source code repository .

如果您想要计时器并且您的主线程没有进行协作多任务处理,我建议您重构您的代码,以便您可以从其他线程使用它。

关于python - threading.Timer 是否在单独的线程中打开函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32898095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com