如何使 python 线程倒计时然后执行操作?
How can I make a python thread count down and then perform an action?
我有一个脚本可以访问 Telegram 机器人的 api,但遗憾的是它一次只能处理一条消息。
我的最终目标是让它在有人开始游戏时启动一个计时器线程,并在一定时间后(如果他们还没有赢得游戏)它会重置游戏以避免阻止另一个用户进入小组玩游戏(我将其设置为一次只玩一个游戏以避免混淆)。
例如:
我试过的一个单词解读游戏:
import time
import telepot
def handle(msg):
message_text = msg['text']
message_location_id = msg['chat']['id']
global game_active
global word_to_unscramble
if message_text == '/newgame':
game_active = True
<game function, defines word_to_unscramble>
time.sleep(30)
if game_active:
game_active = False
word_to_unscramble = None
bot.sendMessage(message_location_id, 'Sorry the answer was ' + word_to_unscramble)
if message_text == 'word_to_unscramble':
game_active = False
bot.sendMessage(message_location_id, 'You win!')
# I added this part in as an echo, just to see when it processed the message
if 'text' in msg:
bot.sendMessage(message_location_id, message_text)
game_active = False
word_to_unscramble = None
bot = telepot.Bot('<my api token>')
bot.message_loop(handle)
但是,使用此代码,它将接收并处理第一条消息,然后等待 30 秒,发送失败的代码,然后处理第二条消息。
我不太熟悉线程处理过程,所以有没有一种方法可以将其设置为启动一个新线程来处理倒数计时器,以便它可以继续处理消息,或者全部丢失原因?
如果无法使用我当前访问电报的方法设置计时器 api,更聪明的方法是什么?
还没有研究过 python-telegram-bot,但是我所知道的关于 Python 中定时器的使用是使用 sched
python 代码。因为在您的应用中 multithreading
会更有意义,为此您可以留意 threading.Timer
class.
我有一个脚本可以访问 Telegram 机器人的 api,但遗憾的是它一次只能处理一条消息。
我的最终目标是让它在有人开始游戏时启动一个计时器线程,并在一定时间后(如果他们还没有赢得游戏)它会重置游戏以避免阻止另一个用户进入小组玩游戏(我将其设置为一次只玩一个游戏以避免混淆)。
例如:
我试过的一个单词解读游戏:
import time
import telepot
def handle(msg):
message_text = msg['text']
message_location_id = msg['chat']['id']
global game_active
global word_to_unscramble
if message_text == '/newgame':
game_active = True
<game function, defines word_to_unscramble>
time.sleep(30)
if game_active:
game_active = False
word_to_unscramble = None
bot.sendMessage(message_location_id, 'Sorry the answer was ' + word_to_unscramble)
if message_text == 'word_to_unscramble':
game_active = False
bot.sendMessage(message_location_id, 'You win!')
# I added this part in as an echo, just to see when it processed the message
if 'text' in msg:
bot.sendMessage(message_location_id, message_text)
game_active = False
word_to_unscramble = None
bot = telepot.Bot('<my api token>')
bot.message_loop(handle)
但是,使用此代码,它将接收并处理第一条消息,然后等待 30 秒,发送失败的代码,然后处理第二条消息。
我不太熟悉线程处理过程,所以有没有一种方法可以将其设置为启动一个新线程来处理倒数计时器,以便它可以继续处理消息,或者全部丢失原因?
如果无法使用我当前访问电报的方法设置计时器 api,更聪明的方法是什么?
还没有研究过 python-telegram-bot,但是我所知道的关于 Python 中定时器的使用是使用 sched
python 代码。因为在您的应用中 multithreading
会更有意义,为此您可以留意 threading.Timer
class.