mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-07 12:50:03 +08:00
refactor(bot): remove cancel_pending_tasks function and adjust shutdown behavior
This commit is contained in:
@@ -1,5 +1,3 @@
|
|||||||
import asyncio
|
|
||||||
|
|
||||||
import nonebot
|
import nonebot
|
||||||
|
|
||||||
# from nonebot.adapters.discord import Adapter as DiscordAdapter
|
# from nonebot.adapters.discord import Adapter as DiscordAdapter
|
||||||
@@ -18,28 +16,7 @@ driver.register_adapter(OneBotV11Adapter)
|
|||||||
|
|
||||||
from zhenxun.services.db_context import disconnect
|
from zhenxun.services.db_context import disconnect
|
||||||
|
|
||||||
|
|
||||||
async def cancel_pending_tasks():
|
|
||||||
"""在关闭前尽量取消仍在运行的协程,避免关闭后继续访问数据库连接池。"""
|
|
||||||
loop = asyncio.get_running_loop()
|
|
||||||
current = asyncio.current_task(loop=loop)
|
|
||||||
pending = [
|
|
||||||
task
|
|
||||||
for task in asyncio.all_tasks(loop)
|
|
||||||
if task is not current and not task.done()
|
|
||||||
]
|
|
||||||
if not pending:
|
|
||||||
return
|
|
||||||
|
|
||||||
for task in pending:
|
|
||||||
task.cancel()
|
|
||||||
|
|
||||||
await asyncio.gather(*pending, return_exceptions=True)
|
|
||||||
|
|
||||||
|
|
||||||
# driver.on_startup(init)
|
# driver.on_startup(init)
|
||||||
# 先取消可能在跑的任务,再断开数据库,避免 pool closing 异常
|
|
||||||
driver.on_shutdown(cancel_pending_tasks)
|
|
||||||
driver.on_shutdown(disconnect)
|
driver.on_shutdown(disconnect)
|
||||||
|
|
||||||
# nonebot.load_builtin_plugins("echo")
|
# nonebot.load_builtin_plugins("echo")
|
||||||
|
|||||||
Reference in New Issue
Block a user