mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-20 11:40:13 +08:00
chore: cancel pending tasks before db disconnect on shutdown
This commit is contained in:
@@ -1,3 +1,5 @@
|
|||||||
|
import asyncio
|
||||||
|
|
||||||
import nonebot
|
import nonebot
|
||||||
|
|
||||||
# from nonebot.adapters.discord import Adapter as DiscordAdapter
|
# from nonebot.adapters.discord import Adapter as DiscordAdapter
|
||||||
@@ -16,7 +18,28 @@ 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