Ver código fonte

adding ui.on_shutdown and cleaning up all running tasks for quicker restart behaviour

Rodja Trappe 3 anos atrás
pai
commit
d67cb3d15e
4 arquivos alterados com 28 adições e 3 exclusões
  1. 3 1
      main.py
  2. 16 2
      nicegui/nicegui.py
  3. 3 0
      nicegui/timer.py
  4. 6 0
      nicegui/ui.py

+ 3 - 1
main.py

@@ -111,7 +111,9 @@ with (example(binding)):
 
 lifecycle = '''### Lifecycle
 
-You can run a coroutine on startup as a parallel task by passing it to `ui.on_startup`.
+You can run a function or coroutine on startup as a parallel task by passing it to `ui.on_startup`.
+If NiceGui is shut down or restarted the tasks will be automatically canceled (for example when you make a code change).
+You can also execude cleanup code with `ui.on_shutdown`.
 '''
 with (example(lifecycle)):
 

+ 16 - 2
nicegui/nicegui.py

@@ -44,13 +44,27 @@ async def binding_loop():
         binding.update()
         await asyncio.sleep(0.1)
 
+def create_task(coro):
+    loop = asyncio.get_event_loop()
+    return loop.create_task(coro)
+
+tasks = []
+
 @jp.app.on_event('startup')
 def startup():
-    [jp.run_task(t) for t in Timer.tasks]
+    global tasks
+    tasks += [create_task(t) for t in Timer.tasks]
+    tasks += [create_task(t) for t in Ui.startup_tasks if isinstance(t, Awaitable)]
     [t() for t in Ui.startup_tasks if isinstance(t, Callable)]
-    [jp.run_task(t) for t in Ui.startup_tasks if isinstance(t, Awaitable)]
     jp.run_task(binding_loop())
 
+@ jp.app.on_event('shutdown')
+def shutdown():
+    [create_task(t) for t in Ui.shutdown_tasks if isinstance(t, Awaitable)]
+    [t() for t in Ui.shutdown_tasks if isinstance(t, Callable)]
+    # # also abort all running startup tasks
+    [t.cancel() for t in tasks]
+
 Element.wp = wp
 Element.view_stack = [main]
 

+ 3 - 0
nicegui/timer.py

@@ -2,6 +2,7 @@ import asyncio
 import time
 import traceback
 from typing import Awaitable
+from asyncio.exceptions import CancelledError
 from binding import BindableProperty
 from .elements.element import Element
 from .utils import handle_exceptions
@@ -42,6 +43,8 @@ class Timer:
                         await parent.update()
                     dt = time.time() - start
                     await asyncio.sleep(interval - dt)
+                except CancelledError:
+                    pass
                 except:
                     traceback.print_exc()
                     await asyncio.sleep(interval)

+ 6 - 0
nicegui/ui.py

@@ -34,3 +34,9 @@ class Ui:
     def on_startup(self, task: Union[Callable, Awaitable]):
 
         self.startup_tasks.append(task)
+
+    shutdown_tasks: List[Union[Callable, Awaitable]] = []
+
+    def on_shutdown(self, task: Union[Callable, Awaitable]):
+
+        self.shutdown_tasks.append(task)