如何更改我的代码以纠正 python(pyTelegramBotAPI) 线程只能启动一次?

问题描述

我创建了一个电报机器人。我在按钮上启动计时器。代码如下:

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

    def run(self):            
            time.sleep(5)
            print("my thread")     
                        
stopFlag = Event()
thread = MyThread(stopFlag)

@bot.message_handler(content_types=['text'])
def buttons(message):
    if message.chat.type == 'private':
        if message.text == 'Запуск таймера 1':
            if thread.is_alive():
                bot.send_message(message.chat.id,"wait for the timer to end")                
            else: 
                thread.start()
                bot.send_message(message.chat.id,"timer started!")

当我在计时器到期后单击按钮时,我得到“线程只能运行一次”,这是有道理的,因为我没有代码的多线程版本。如何做一个多线程选项,让定时器可以无限启动?

解决方法

来自threading docs

is_alive()

返回线程是否存活。

这个方法在 run() 方法开始之前返回 True,直到 就在 run() 方法终止之后。

完成后,thread.is_alive() 再次返回您 False 并且您尝试第二次运行它失败了。您需要初始化一个新的 MyThread 对象才能再次运行它。