【问题标题】:how to change my code to correct python(pyTelegramBotAPI) threads can only be started once?如何更改我的代码以更正 python(pyTelegramBotAPI) 线程只能启动一次?
【发布时间】:2021-03-23 18:17:05
【问题描述】:

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

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

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

【问题讨论】:

    标签: python python-3.x multithreading telegram py-telegram-bot-api


    【解决方案1】:

    来自threading docs

    is_alive()

    返回线程是否存活。

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

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

    【讨论】:

    • 但是如何重新运行MyThread?它会触发 1 次,但我需要不断调用它。也许我选择了错误的方式?
    • 或者如何再次正确初始化?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2015-03-24
    • 2020-12-13
    • 1970-01-01
    相关资源
    最近更新 更多