feat: 优化配置重载逻辑,增加重载状态标记和时间检查

pull/76/head
墨梓柒 2026-01-03 02:31:22 +08:00
parent d40663709c
commit 66a1c08405
No known key found for this signature in database
GPG Key ID: 4A65B9DBA35F7635
1 changed files with 36 additions and 17 deletions

View File

@ -37,6 +37,8 @@ class ConfigManager:
self._reload_debounce_task: Optional[asyncio.Task] = None self._reload_debounce_task: Optional[asyncio.Task] = None
self._debounce_delay: float = 0.5 # 防抖延迟(秒) self._debounce_delay: float = 0.5 # 防抖延迟(秒)
self._loop: Optional[asyncio.AbstractEventLoop] = None # 事件循环引用 self._loop: Optional[asyncio.AbstractEventLoop] = None # 事件循环引用
self._is_reloading: bool = False # 标记是否正在重载
self._last_reload_trigger: float = 0.0 # 最后一次触发重载的时间
def load(self, config_path: str = "config.toml") -> None: def load(self, config_path: str = "config.toml") -> None:
"""加载配置文件 """加载配置文件
@ -247,14 +249,29 @@ class ConfigManager:
async def _debounced_reload(self) -> None: async def _debounced_reload(self) -> None:
"""防抖重载:避免短时间内多次文件修改事件导致重复重载""" """防抖重载:避免短时间内多次文件修改事件导致重复重载"""
# 取消之前的防抖任务 import time
if self._reload_debounce_task and not self._reload_debounce_task.done():
self._reload_debounce_task.cancel() # 记录当前触发时间
trigger_time = time.time()
self._last_reload_trigger = trigger_time
# 等待防抖延迟 # 等待防抖延迟
await asyncio.sleep(self._debounce_delay) await asyncio.sleep(self._debounce_delay)
# 检查是否有更新的触发
if self._last_reload_trigger > trigger_time:
# 有更新的触发,放弃本次重载
logger.debug("放弃过时的重载请求")
return
# 检查是否已有重载在进行
if self._is_reloading:
logger.debug("重载已在进行中,跳过")
return
# 执行重载 # 执行重载
self._is_reloading = True
try:
modified_time = datetime.fromtimestamp( modified_time = datetime.fromtimestamp(
os.path.getmtime(self._config_path) os.path.getmtime(self._config_path)
).strftime("%Y-%m-%d %H:%M:%S") ).strftime("%Y-%m-%d %H:%M:%S")
@ -270,6 +287,8 @@ class ConfigManager:
"配置文件重载失败!请检查配置文件格式是否正确。\n" "配置文件重载失败!请检查配置文件格式是否正确。\n"
"当前仍使用旧配置运行,修复配置文件后将自动重试。" "当前仍使用旧配置运行,修复配置文件后将自动重试。"
) )
finally:
self._is_reloading = False
def __repr__(self) -> str: def __repr__(self) -> str:
watching = self._observer is not None and self._observer.is_alive() watching = self._observer is not None and self._observer.is_alive()