timer.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import asyncio
  2. import time
  3. import traceback
  4. from .elements.element import Element
  5. from .utils import handle_exceptions
  6. class Timer:
  7. tasks = []
  8. def __init__(self, interval, callback, *, once=False):
  9. """Timer
  10. One major drive behind the creation of NiceGUI was the necessity to have an simple approach to update the interface in regular intervals. For example to show a graph with incomming measurements.
  11. :param interval: the interval in which the timer is been called
  12. :param callback: function to execute when interval elapses
  13. :param once: weather the callback is only executed once after an delay specified by `interval`; default is False
  14. """
  15. parent = Element.view_stack[-1]
  16. async def timeout():
  17. await asyncio.sleep(interval)
  18. handle_exceptions(callback)()
  19. await parent.update()
  20. async def loop():
  21. while True:
  22. try:
  23. start = time.time()
  24. handle_exceptions(callback)()
  25. await parent.update()
  26. dt = time.time() - start
  27. await asyncio.sleep(interval - dt)
  28. except:
  29. traceback.print_exc()
  30. await asyncio.sleep(interval)
  31. self.tasks.append(timeout() if once else loop())