Timer thread. Note: This is only used for transports not supporting AsyncIO.
| 22 | |
| 23 | |
| 24 | class Timer(threading.Thread): |
| 25 | """Timer thread. |
| 26 | |
| 27 | Note: |
| 28 | This is only used for transports not supporting AsyncIO. |
| 29 | """ |
| 30 | |
| 31 | Entry = Entry |
| 32 | Schedule = Schedule |
| 33 | |
| 34 | running: bool = False |
| 35 | on_tick: Optional[Callable[[float], None]] = None |
| 36 | |
| 37 | _timer_count: count = count(1) |
| 38 | |
| 39 | if TIMER_DEBUG: # pragma: no cover |
| 40 | def start(self, *args: Any, **kwargs: Any) -> None: |
| 41 | import traceback |
| 42 | print('- Timer starting') |
| 43 | traceback.print_stack() |
| 44 | super().start(*args, **kwargs) |
| 45 | |
| 46 | def __init__(self, schedule: Optional[Schedule] = None, |
| 47 | on_error: Optional[Callable[[Exception], None]] = None, |
| 48 | on_tick: Optional[Callable[[float], None]] = None, |
| 49 | on_start: Optional[Callable[['Timer'], None]] = None, |
| 50 | max_interval: Optional[float] = None, **kwargs: Any) -> None: |
| 51 | self.schedule = schedule if schedule is not None else self.Schedule( |
| 52 | on_error=on_error, max_interval=max_interval) |
| 53 | self.on_start = on_start |
| 54 | self.on_tick = on_tick or self.on_tick |
| 55 | super().__init__() |
| 56 | # `_is_stopped` is likely to be an attribute on `Thread` objects so we |
| 57 | # double underscore these names to avoid shadowing anything and |
| 58 | # potentially getting confused by the superclass turning these into |
| 59 | # something other than an `Event` instance (e.g. a `bool`) |
| 60 | self.__is_shutdown = threading.Event() |
| 61 | self.__is_stopped = threading.Event() |
| 62 | self.mutex = threading.Lock() |
| 63 | self.not_empty = threading.Condition(self.mutex) |
| 64 | self.daemon = True |
| 65 | self.name = f'Timer-{next(self._timer_count)}' |
| 66 | |
| 67 | def _next_entry(self) -> Optional[float]: |
| 68 | with self.not_empty: |
| 69 | delay: Optional[float] |
| 70 | entry: Optional[Entry] |
| 71 | delay, entry = next(self.scheduler) |
| 72 | if entry is None: |
| 73 | if delay is None: |
| 74 | self.not_empty.wait(1.0) |
| 75 | return delay |
| 76 | return self.schedule.apply_entry(entry) |
| 77 | __next__ = next = _next_entry # for 2to3 |
| 78 | |
| 79 | def run(self) -> None: |
| 80 | try: |
| 81 | self.running = True |
no outgoing calls