我正在使用 python-telegram-bot 开发一个电报机器人。它就像一个股票筛选器,它会在每个给定的时间间隔分析市场并将结果发送给订阅该指标的用户。问题是我不希望机器人在分析市场(它获取数据并进行大量计算)时被阻止(用户不断与其交互)。所以我认为我需要在不同的线程中执行此操作,但我无法使其与 asyncio 一起工作
这是例子:
async def run_screener(bot):
while True:
async def heavy_computations():
for i in range(5):
await asyncio.sleep(2)
print("Doing computations")
compute = threading.Thread(target=lambda: asyncio.run(heavy_computations()))
compute.start()
compute.join() # <--- This is blocking the bot
# Computations are done, now send the results with the bot
async with bot: # <--- For some reason this line blocks the bot forever, even without .join()
for user_id in users:
await bot.send_message(text=results, chat_id=user_id)
await asyncio.sleep(compute_next_time())
async def main():
application = buildBot()
async with application:
await application.start()
await application.updater.start_polling()
await run_screener(application.bot)
await application.updater.stop()
await application.stop()
asyncio.run(main())
t = threading.Thread(target=foo, args=(...))
t.start()
t.join() # <--- This is ALWAYS a mistake.
永远不会有任何理由start
一个线程,然后立即
join
它。您抱怨 compute.join()
“阻止”呼叫者,但阻止呼叫者是 join()
唯一应该做的事情。compute.join()
对
compute
线程没有任何作用。它对任何线程或其他任何东西都没有任何作用。 compute.join()
不执行任何操作,直到 compute
线程完成,然后返回。就是这样。这就是它的全部作用。我对电报一无所知。我不知道你实际上想做什么,但听起来你需要重新构造你的代码,以便run_screener
不会
等到“计算完成”。相反,您要么需要让新线程“使用机器人发送结果”,要么需要让新线程触发一些事件,该事件将导致某些other线程“使用机器人发送结果” .”