0

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

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!")

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

4

1 回答 1

0

线程文档

活着()

返回线程是否存活。

此方法在 run() 方法开始之前直到 run() 方法终止之后才返回 True。

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

于 2021-03-23T18:32:30.277 回答