timer.py 878 B

12345678910111213141516171819202122232425262728293031323334
  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. parent = Element.view_stack[-1]
  10. async def timeout():
  11. await asyncio.sleep(interval)
  12. handle_exceptions(callback)()
  13. await parent.update()
  14. async def loop():
  15. while True:
  16. try:
  17. start = time.time()
  18. handle_exceptions(callback)()
  19. await parent.update()
  20. dt = time.time() - start
  21. await asyncio.sleep(interval - dt)
  22. except:
  23. traceback.print_exc()
  24. await asyncio.sleep(interval)
  25. self.tasks.append(timeout() if once else loop())