浏览代码

make sure to cleanup timers even if client fails to connect

Falko Schindler 2 年之前
父节点
当前提交
4fa93056d2
共有 1 个文件被更改,包括 29 次插入25 次删除
  1. 29 25
      nicegui/functions/timer.py

+ 29 - 25
nicegui/functions/timer.py

@@ -37,33 +37,37 @@ class Timer:
             globals.app.on_startup(coroutine)
 
     async def _run_once(self) -> None:
-        with self.slot:
-            await self._connected()
-            await asyncio.sleep(self.interval)
-            if globals.state not in [globals.State.STOPPING, globals.State.STOPPED]:
-                await self._invoke_callback()
-        self.cleanup()
+        try:
+            with self.slot:
+                await self._connected()
+                await asyncio.sleep(self.interval)
+                if globals.state not in [globals.State.STOPPING, globals.State.STOPPED]:
+                    await self._invoke_callback()
+        finally:
+            self.cleanup()
 
     async def _run_in_loop(self) -> None:
-        with self.slot:
-            await self._connected()
-            while True:
-                if self.slot.parent.client.id not in globals.clients:
-                    break
-                if globals.state in [globals.State.STOPPING, globals.State.STOPPED]:
-                    break
-                try:
-                    start = time.time()
-                    if self.active:
-                        await self._invoke_callback()
-                    dt = time.time() - start
-                    await asyncio.sleep(self.interval - dt)
-                except asyncio.CancelledError:
-                    break
-                except:
-                    globals.log.exception('Exception in timer callback')
-                    await asyncio.sleep(self.interval)
-        self.cleanup()
+        try:
+            with self.slot:
+                await self._connected()
+                while True:
+                    if self.slot.parent.client.id not in globals.clients:
+                        break
+                    if globals.state in [globals.State.STOPPING, globals.State.STOPPED]:
+                        break
+                    try:
+                        start = time.time()
+                        if self.active:
+                            await self._invoke_callback()
+                        dt = time.time() - start
+                        await asyncio.sleep(self.interval - dt)
+                    except asyncio.CancelledError:
+                        break
+                    except:
+                        globals.log.exception('Exception in timer callback')
+                        await asyncio.sleep(self.interval)
+        finally:
+            self.cleanup()
 
     async def _invoke_callback(self) -> None:
         try: