Jelajahi Sumber

make sure to cleanup timers even if client fails to connect

Falko Schindler 2 tahun lalu
induk
melakukan
4fa93056d2
1 mengubah file dengan 29 tambahan dan 25 penghapusan
  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: