如何在不阻塞AsyncTelebot的情况下使用aioschedule调度器
修复AsyncTelebot与aioschedule共存时的阻塞问题
问题根源
start_bot函数中多余的while True嵌套:bot.polling(none_stop=True)本身已实现持续运行、异常重连的循环逻辑,外层再加循环会干扰事件调度逻辑。run_notifications中使用await asyncio.sleep(0):该操作会让事件循环频繁切换任务,过于密集的循环会占用大量CPU资源,挤压机器人消息处理的时间片,导致机器人无法响应请求。
修复代码
1. 修正start_bot函数
移除多余的外层循环,保留bot.polling原生的持续运行逻辑:
async def start_bot(): # 添加skip_pending=True可跳过积累的旧消息,提升响应速度 await bot.polling(none_stop=True, skip_pending=True)
2. 优化调度器循环
将await asyncio.sleep(0)改为合理的睡眠时间(如1秒),降低循环频率,给机器人留出足够的消息处理时间:
async def run_notifications(): schedule.every(10).seconds.do(send_notifications) while True: await schedule.run_pending() await asyncio.sleep(1)
3. 完整修正后的核心代码
import asyncio import aioschedule as schedule import datetime ... async def send_price_update_notifications(): print("Check notifications: " + str(datetime.datetime.now())) ... async def send_notifications(): await send_price_update_notifications() async def run_notifications(): schedule.every(10).seconds.do(send_notifications) while True: await schedule.run_pending() await asyncio.sleep(1) async def start_bot(): await bot.polling(none_stop=True, skip_pending=True) async def main(): task1 = asyncio.create_task(run_notifications()) task2 = asyncio.create_task(start_bot()) await asyncio.gather(task1, task2) if __name__ == '__main__': asyncio.run(main())
额外说明
- 如果调度任务需要更高精度,可将睡眠时间调整为0.1秒,既保证调度准确性,又不会过度占用资源。
- 确保
bot实例是通过AsyncTeleBot创建的,而非同步版TeleBot,这是异步运行的前提。
内容的提问来源于stack exchange,提问作者foxbane
相关产品推荐
相关产品推荐

