瀏覽代碼

let timer support async callbacks

Falko Schindler 3 年之前
父節點
當前提交
c20328a923
共有 2 個文件被更改,包括 15 次插入6 次删除
  1. 6 6
      nicegui/timer.py
  2. 9 0
      nicegui/utils.py

+ 6 - 6
nicegui/timer.py

@@ -1,10 +1,10 @@
 import asyncio
 import time
 import traceback
-from typing import Awaitable
+from typing import Awaitable, Callable, Union
 from binding import BindableProperty
 from .elements.element import Element
-from .utils import handle_exceptions
+from .utils import handle_exceptions, handle_awaitable
 
 class Timer:
 
@@ -12,7 +12,7 @@ class Timer:
 
     active = BindableProperty
 
-    def __init__(self, interval: float, callback: Awaitable, *, active: bool = True, once: bool = False):
+    def __init__(self, interval: float, callback: Union[Callable, Awaitable], *, active: bool = True, once: bool = False):
         """Timer
 
         One major drive behind the creation of NiceGUI was the necessity to have a simple approach to update the interface in regular intervals, for example to show a graph with incomming measurements.
@@ -20,7 +20,7 @@ class Timer:
         The parent view container will be updated automatically, as long as the callback does not return `False`.
 
         :param interval: the interval in which the timer is called
-        :param callback: function to execute when interval elapses (can return `False` to prevent view update)
+        :param callback: function or coroutine to execute when interval elapses (can return `False` to prevent view update)
         :param active: whether the callback should be executed or not
         :param once: whether the callback is only executed once after a delay specified by `interval`; default is `False`
         """
@@ -31,7 +31,7 @@ class Timer:
         async def timeout():
 
             await asyncio.sleep(interval)
-            handle_exceptions(callback)()
+            await handle_exceptions(handle_awaitable(callback))()
             await parent.update()
 
         async def loop():
@@ -40,7 +40,7 @@ class Timer:
                 try:
                     start = time.time()
                     if self.active:
-                        needs_update = handle_exceptions(callback)()
+                        needs_update = await handle_exceptions(handle_awaitable(callback))()
                         if needs_update != False:
                             await parent.update()
                     dt = time.time() - start

+ 9 - 0
nicegui/utils.py

@@ -1,3 +1,4 @@
+import asyncio
 import traceback
 
 class EventArguments:
@@ -23,3 +24,11 @@ def handle_exceptions(func):
         except Exception:
             traceback.print_exc()
     return inner_function
+
+def handle_awaitable(func):
+    async def inner_function(*args, **kwargs):
+        if asyncio.iscoroutinefunction(func):
+            return await func(*args, **kwargs)
+        else:
+            return func(*args, **kwargs)
+    return inner_function