timer.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import asyncio
  2. import time
  3. import traceback
  4. from binding import BindableProperty
  5. from .elements.element import Element
  6. from .utils import handle_exceptions
  7. class Timer:
  8. tasks = []
  9. active = BindableProperty
  10. def __init__(self, interval, callback, *, active=True, once=False):
  11. """Timer
  12. 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.
  13. :param interval: the interval in which the timer is been called
  14. :param callback: function to execute when interval elapses
  15. :param active: weather timer should run or be paused
  16. :param once: weather the callback is only executed once after an delay specified by `interval`; default is False
  17. """
  18. parent = Element.view_stack[-1]
  19. self.active = active
  20. async def timeout():
  21. await asyncio.sleep(interval)
  22. handle_exceptions(callback)()
  23. await parent.update()
  24. async def loop():
  25. while True:
  26. try:
  27. start = time.time()
  28. if self.active:
  29. handle_exceptions(callback)()
  30. await parent.update()
  31. dt = time.time() - start
  32. await asyncio.sleep(interval - dt)
  33. except:
  34. traceback.print_exc()
  35. await asyncio.sleep(interval)
  36. self.tasks.append(timeout() if once else loop())