如何将我的代码更改为正确的python(python)线程只能启动一次?

2024-06-02 06:47:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 代码textselfmessageifinitdefbot
1条回答
网友
1楼 · 发布于 2024-06-02 06:47:34

threading docs开始:

is_alive()

Return whether the thread is alive.

This method returns True just before the run() method starts until just after the run() method terminates.

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

相关问题 更多 >