infinite_timer.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from threading import Timer
  2. from lib.util import EBC
  3. class InfiniteTimer(EBC):
  4. """
  5. A Timer class that does not stop, unless you want it to.
  6. https://stackoverflow.com/a/41450617
  7. """
  8. def __init__(self, seconds, target, daemon=True):
  9. self._should_continue = False
  10. self.is_running = False
  11. self.seconds = seconds
  12. self.target = target
  13. self.thread = None
  14. self.daemon = daemon
  15. def _handle_target(self):
  16. self.is_running = True
  17. self.target()
  18. self.is_running = False
  19. self._start_timer()
  20. def _start_timer(self):
  21. if self._should_continue: # Code could have been running when cancel was called.
  22. self.thread = Timer(self.seconds, self._handle_target)
  23. self.thread.daemon = self.daemon
  24. self.thread.start()
  25. def start(self):
  26. if not self._should_continue and not self.is_running:
  27. self._should_continue = True
  28. self._start_timer()
  29. else:
  30. print("Timer already started or running, please wait if you're restarting.")
  31. def cancel(self):
  32. if self.thread is not None:
  33. self._should_continue = False # Just in case thread is running and cancel fails.
  34. self.thread.cancel()
  35. else:
  36. print("Timer never started or failed to initialize.")