timer.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """
  2. Managing time and events
  3. """
  4. import time
  5. class TimeoutError(Exception):
  6. """The event has timed out."""
  7. class EventTimer(object):
  8. """Do something at an interval.
  9. .. attribute:: interval
  10. How often we call the event (in seconds).
  11. .. attribute:: event
  12. The event callable to run every ``interval`` seconds.
  13. .. attribute:: last_triggered
  14. The last time, in unix timestamp format, the event was executed.
  15. """
  16. def __init__(self, event, interval=None):
  17. self.event = event
  18. self.interval = interval
  19. self.last_triggered = None
  20. def tick(self):
  21. """Run a event timer clock tick.
  22. When the interval has run, the event will be triggered.
  23. If interval is not set, the event will never be triggered.
  24. """
  25. if not self.interval: # never trigger if no interval.
  26. return
  27. if not self.last_triggered or \
  28. time.time() > self.last_triggered + self.interval:
  29. self.event()
  30. self.last_triggered = time.time()
  31. class TimeoutTimer(object):
  32. """A timer that raises :exc:`TimeoutError` exception when the
  33. time has run out.
  34. .. attribute:: timeout
  35. The timeout in seconds.
  36. .. attribute:: time_start
  37. The time when the timeout timer instance was constructed.
  38. """
  39. def __init__(self, timeout, timeout_msg="The operation timed out"):
  40. self.timeout = timeout
  41. self.timeout_msg = timeout_msg
  42. self.time_start = time.time()
  43. def tick(self):
  44. """Run a timeout timer clock tick.
  45. :raises TimeoutError: when :attr:`timeout` seconds has passed.
  46. If :attr:`timeout` is not set, it will never time out.
  47. """
  48. if not self.timeout:
  49. return
  50. if time.time() > self.time_start + self.timeout:
  51. raise TimeoutError(self.timeout_msg)