| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
from __future__ import annotations |
| 20 |
|
| 21 |
from collections.abc import Callable |
| 22 |
from datetime import datetime, timedelta |
| 23 |
|
| 24 |
|
| 25 |
class Hook: |
| 26 |
""" |
| 27 |
Event handler that invokes an arbitrary callback when invoked. |
| 28 |
If the timeout_milliseconds argument is greater than 0, |
| 29 |
the hook will be suspended for n milliseconds after it's being invoked. |
| 30 |
""" |
| 31 |
|
| 32 |
def __init__( |
| 33 |
self, |
| 34 |
callback: Callable[..., object], |
| 35 |
timeout_milliseconds: int = 0, |
| 36 |
*callback_args: object, |
| 37 |
) -> None: |
| 38 |
self.callback = callback |
| 39 |
self.timeout_milliseconds = timeout_milliseconds |
| 40 |
self.callback_args = callback_args |
| 41 |
self.ready_time = datetime.now() |
| 42 |
|
| 43 |
def is_ready(self) -> bool: |
| 44 |
""" |
| 45 |
Returns whether the hook is ready to invoke its callback or not |
| 46 |
""" |
| 47 |
|
| 48 |
return datetime.now() >= self.ready_time |
| 49 |
|
| 50 |
def invoke(self) -> None: |
| 51 |
""" |
| 52 |
Run callback, optionally passing a variable number |
| 53 |
of arguments `callback_args` |
| 54 |
""" |
| 55 |
|
| 56 |
|
| 57 |
if self.timeout_milliseconds > 0: |
| 58 |
self.ready_time = datetime.now() + timedelta( |
| 59 |
milliseconds=self.timeout_milliseconds |
| 60 |
) |
| 61 |
|
| 62 |
self.callback(self.callback_args) |