feat: 添加 _ready_event 以确保文件监视器在启动时准备就绪,优化监控逻辑
This commit is contained in:
@@ -135,7 +135,6 @@ async def test_add_callback_while_watcher_running(tmp_path: Path):
|
|||||||
uuid = watcher.subscribe(callback, paths=[file])
|
uuid = watcher.subscribe(callback, paths=[file])
|
||||||
await watcher.start()
|
await watcher.start()
|
||||||
try:
|
try:
|
||||||
await asyncio.sleep(0.5) # 等待 watcher 建立 baseline
|
|
||||||
with file.open("w") as f:
|
with file.open("w") as f:
|
||||||
f.write("change")
|
f.write("change")
|
||||||
await _wait_for(lambda: calls >= 1)
|
await _wait_for(lambda: calls >= 1)
|
||||||
|
|||||||
@@ -119,7 +119,9 @@ class FileWatcher:
|
|||||||
if not self._subscriptions:
|
if not self._subscriptions:
|
||||||
raise RuntimeError("启动文件监视器前必须至少注册一个订阅")
|
raise RuntimeError("启动文件监视器前必须至少注册一个订阅")
|
||||||
self._running = True
|
self._running = True
|
||||||
|
self._ready_event = asyncio.Event()
|
||||||
self._task = asyncio.create_task(self._run())
|
self._task = asyncio.create_task(self._run())
|
||||||
|
await self._ready_event.wait()
|
||||||
|
|
||||||
async def stop(self) -> None:
|
async def stop(self) -> None:
|
||||||
if not self._running:
|
if not self._running:
|
||||||
@@ -138,9 +140,18 @@ class FileWatcher:
|
|||||||
async def _run(self) -> None:
|
async def _run(self) -> None:
|
||||||
while self._running:
|
while self._running:
|
||||||
try:
|
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:
|
if not self._running:
|
||||||
break
|
break
|
||||||
|
if not changes:
|
||||||
|
continue
|
||||||
normalized_changes = self._normalize_changes(changes)
|
normalized_changes = self._normalize_changes(changes)
|
||||||
if not normalized_changes:
|
if not normalized_changes:
|
||||||
continue
|
continue
|
||||||
|
|||||||
Reference in New Issue
Block a user