feat: 添加 _ready_event 以确保文件监视器在启动时准备就绪,优化监控逻辑

This commit is contained in:
DrSmoothl
2026-03-09 15:04:58 +08:00
parent 7e2ab0d71d
commit dfa944b368
2 changed files with 12 additions and 2 deletions

View File

@@ -135,7 +135,6 @@ async def test_add_callback_while_watcher_running(tmp_path: Path):
uuid = watcher.subscribe(callback, paths=[file])
await watcher.start()
try:
await asyncio.sleep(0.5) # 等待 watcher 建立 baseline
with file.open("w") as f:
f.write("change")
await _wait_for(lambda: calls >= 1)

View File

@@ -119,7 +119,9 @@ class FileWatcher:
if not self._subscriptions:
raise RuntimeError("启动文件监视器前必须至少注册一个订阅")
self._running = True
self._ready_event = asyncio.Event()
self._task = asyncio.create_task(self._run())
await self._ready_event.wait()
async def stop(self) -> None:
if not self._running:
@@ -138,9 +140,18 @@ class FileWatcher:
async def _run(self) -> None:
while self._running:
try:
async for changes in awatch(*self._paths, debounce=self._debounce_ms, force_polling=self._force_polling):
async for changes in awatch(
*self._paths,
debounce=self._debounce_ms,
force_polling=self._force_polling,
yield_on_timeout=True,
):
if not self._ready_event.is_set():
self._ready_event.set()
if not self._running:
break
if not changes:
continue
normalized_changes = self._normalize_changes(changes)
if not normalized_changes:
continue