首页 > 后端开发 > Python教程 > 为什么'threading.Timer”重复启动时会引发'RuntimeError”?

为什么'threading.Timer”重复启动时会引发'RuntimeError”?

DDD
发布: 2024-11-10 17:20:03
原创
369 人浏览过

Why Does `threading.Timer` Raise a `RuntimeError` When Repeatedly Started?

使用重复计时器进行线程

为了每隔“n”秒定期执行一个函数,Python threading.Timer 类提供了一个实用的解决方案。然而,当您需要重复启动、停止和重置时,使用此计时器可能会很棘手。

假设您想每 0.5 秒触发一个函数。您可以尝试以下操作:

import threading

def function_to_execute():
    # Your function code here

t = threading.Timer(0.5, function_to_execute)

while True:
    t.cancel()
    t.start()
登录后复制

但是,此代码将引发 RuntimeError,抱怨多次启动线程。这是为什么?

默认情况下,定时器线程的 start() 方法只能调用一次。但由于我们反复取消和重新启动计时器,所以遇到了这个问题。

创建可重用的计时器线程

要克服这个限制,更好的方法是仅启动一次计时器线程。在线程内部,我们将实现重复执行函数:

import threading

class MyThread(threading.Thread):
    def __init__(self, event):
        threading.Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            # Execute your function here

# Create a stop event
stopFlag = threading.Event()

# Start the timer thread
thread = MyThread(stopFlag)
thread.start()
登录后复制

通过此设置,计时器线程将每 0.5 秒连续执行一次函数。要停止计时器,只需设置 stopFlag 事件:

# Stop the timer
stopFlag.set()
登录后复制

使用此方法,您可以根据需要重复启动、停止和重置计时器,而不会遇到 RuntimeError。

以上是为什么'threading.Timer”重复启动时会引发'RuntimeError”?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板