fix(memory): 修复定时清理任务的异步执行问题
This commit is contained in:
54
bot.py
54
bot.py
@@ -68,6 +68,7 @@ uvicorn_server = None
|
|||||||
driver = None
|
driver = None
|
||||||
app = None
|
app = None
|
||||||
loop = None
|
loop = None
|
||||||
|
main_system = None
|
||||||
|
|
||||||
|
|
||||||
async def request_shutdown() -> bool:
|
async def request_shutdown() -> bool:
|
||||||
@@ -99,8 +100,58 @@ def easter_egg():
|
|||||||
async def graceful_shutdown():
|
async def graceful_shutdown():
|
||||||
try:
|
try:
|
||||||
logger.info("正在优雅关闭麦麦...")
|
logger.info("正在优雅关闭麦麦...")
|
||||||
|
|
||||||
|
# 首先停止服务器组件,避免网络连接被强制关闭
|
||||||
|
try:
|
||||||
|
global server
|
||||||
|
if server and hasattr(server, 'shutdown'):
|
||||||
|
logger.info("正在关闭服务器...")
|
||||||
|
await server.shutdown()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"关闭服务器时出错: {e}")
|
||||||
|
|
||||||
|
# 停止聊天管理器
|
||||||
|
try:
|
||||||
|
from src.chat.message_receive.chat_stream import get_chat_manager
|
||||||
|
chat_manager = get_chat_manager()
|
||||||
|
if hasattr(chat_manager, '_stop_auto_save'):
|
||||||
|
logger.info("正在停止聊天管理器...")
|
||||||
|
chat_manager._stop_auto_save()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"停止聊天管理器时出错: {e}")
|
||||||
|
|
||||||
|
# 停止情绪管理器
|
||||||
|
try:
|
||||||
|
from src.mood.mood_manager import mood_manager
|
||||||
|
if hasattr(mood_manager, 'stop'):
|
||||||
|
logger.info("正在停止情绪管理器...")
|
||||||
|
await mood_manager.stop()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"停止情绪管理器时出错: {e}")
|
||||||
|
|
||||||
|
# 停止记忆系统
|
||||||
|
try:
|
||||||
|
from src.chat.memory_system.memory_manager import memory_manager
|
||||||
|
if hasattr(memory_manager, 'shutdown'):
|
||||||
|
logger.info("正在停止记忆系统...")
|
||||||
|
await memory_manager.shutdown()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"停止记忆系统时出错: {e}")
|
||||||
|
|
||||||
|
# 停止MainSystem
|
||||||
|
try:
|
||||||
|
global main_system
|
||||||
|
if main_system and hasattr(main_system, 'shutdown'):
|
||||||
|
logger.info("正在停止MainSystem...")
|
||||||
|
await main_system.shutdown()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"停止MainSystem时出错: {e}")
|
||||||
|
|
||||||
# 停止所有异步任务
|
# 停止所有异步任务
|
||||||
await async_task_manager.stop_and_wait_all_tasks()
|
try:
|
||||||
|
await async_task_manager.stop_and_wait_all_tasks()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"停止异步任务管理器时出错: {e}")
|
||||||
|
|
||||||
# 获取所有剩余任务,排除当前任务
|
# 获取所有剩余任务,排除当前任务
|
||||||
remaining_tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
|
remaining_tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
|
||||||
@@ -233,6 +284,7 @@ if __name__ == "__main__":
|
|||||||
try:
|
try:
|
||||||
# 异步初始化数据库和表结构
|
# 异步初始化数据库和表结构
|
||||||
main_system = loop.run_until_complete(maibot.run())
|
main_system = loop.run_until_complete(maibot.run())
|
||||||
|
global main_system
|
||||||
loop.run_until_complete(maibot.initialize_database_async())
|
loop.run_until_complete(maibot.initialize_database_async())
|
||||||
# 执行初始化和任务调度
|
# 执行初始化和任务调度
|
||||||
loop.run_until_complete(main_system.initialize())
|
loop.run_until_complete(main_system.initialize())
|
||||||
|
|||||||
@@ -226,13 +226,22 @@ class VectorMemoryStorage:
|
|||||||
if self.config.auto_cleanup_interval > 0:
|
if self.config.auto_cleanup_interval > 0:
|
||||||
|
|
||||||
def cleanup_worker():
|
def cleanup_worker():
|
||||||
while not self._stop_cleanup:
|
# 在新线程中创建事件循环
|
||||||
try:
|
loop = asyncio.new_event_loop()
|
||||||
time.sleep(self.config.auto_cleanup_interval)
|
asyncio.set_event_loop(loop)
|
||||||
if not self._stop_cleanup:
|
|
||||||
asyncio.create_task(self._perform_auto_cleanup())
|
try:
|
||||||
except Exception as e:
|
while not self._stop_cleanup:
|
||||||
logger.error(f"定时清理任务出错: {e}")
|
try:
|
||||||
|
time.sleep(self.config.auto_cleanup_interval)
|
||||||
|
if not self._stop_cleanup:
|
||||||
|
# 在线程的事件循环中运行异步清理任务
|
||||||
|
loop.run_until_complete(self._perform_auto_cleanup())
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"定时清理任务出错: {e}")
|
||||||
|
finally:
|
||||||
|
loop.close()
|
||||||
|
logger.debug("清理任务事件循环已关闭")
|
||||||
|
|
||||||
self._cleanup_task = threading.Thread(target=cleanup_worker, daemon=True)
|
self._cleanup_task = threading.Thread(target=cleanup_worker, daemon=True)
|
||||||
self._cleanup_task.start()
|
self._cleanup_task.start()
|
||||||
|
|||||||
55
src/main.py
55
src/main.py
@@ -348,16 +348,55 @@ MoFox_Bot(第三方修改版)
|
|||||||
|
|
||||||
async def schedule_tasks(self):
|
async def schedule_tasks(self):
|
||||||
"""调度定时任务"""
|
"""调度定时任务"""
|
||||||
while True:
|
try:
|
||||||
tasks = [
|
while True:
|
||||||
get_emoji_manager().start_periodic_check_register(),
|
tasks = [
|
||||||
self.app.run(),
|
get_emoji_manager().start_periodic_check_register(),
|
||||||
self.server.run(),
|
self.app.run(),
|
||||||
]
|
self.server.run(),
|
||||||
|
]
|
||||||
|
|
||||||
# 增强记忆系统不需要定时任务,已禁用原有记忆系统的定时任务
|
# 增强记忆系统不需要定时任务,已禁用原有记忆系统的定时任务
|
||||||
|
|
||||||
await asyncio.gather(*tasks)
|
await asyncio.gather(*tasks)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"调度任务发生异常: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def shutdown(self):
|
||||||
|
"""关闭系统组件"""
|
||||||
|
logger.info("正在关闭MainSystem...")
|
||||||
|
|
||||||
|
# 关闭表情管理器
|
||||||
|
try:
|
||||||
|
get_emoji_manager().shutdown()
|
||||||
|
logger.info("表情管理器已关闭")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"关闭表情管理器时出错: {e}")
|
||||||
|
|
||||||
|
# 关闭服务器
|
||||||
|
try:
|
||||||
|
if self.server:
|
||||||
|
await self.server.shutdown()
|
||||||
|
logger.info("服务器已关闭")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"关闭服务器时出错: {e}")
|
||||||
|
|
||||||
|
# 关闭应用 (MessageServer可能没有shutdown方法)
|
||||||
|
try:
|
||||||
|
if self.app:
|
||||||
|
if hasattr(self.app, 'shutdown'):
|
||||||
|
await self.app.shutdown()
|
||||||
|
logger.info("应用已关闭")
|
||||||
|
elif hasattr(self.app, 'stop'):
|
||||||
|
await self.app.stop()
|
||||||
|
logger.info("应用已停止")
|
||||||
|
else:
|
||||||
|
logger.info("应用没有shutdown方法,跳过关闭")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"关闭应用时出错: {e}")
|
||||||
|
|
||||||
|
logger.info("MainSystem关闭完成")
|
||||||
|
|
||||||
# 老记忆系统的定时任务已删除 - 增强记忆系统使用内置的维护机制
|
# 老记忆系统的定时任务已删除 - 增强记忆系统使用内置的维护机制
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user