|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | +from asyncio import ensure_future |
| 4 | +from functools import wraps |
| 5 | +from traceback import format_exception |
| 6 | +from typing import Any, Callable, Coroutine, Optional, Union |
| 7 | + |
| 8 | +from starlette.concurrency import run_in_threadpool |
| 9 | + |
| 10 | +NoArgsNoReturnFuncT = Callable[[], None] |
| 11 | +NoArgsNoReturnAsyncFuncT = Callable[[], Coroutine[Any, Any, None]] |
| 12 | +NoArgsNoReturnDecorator = Callable[ |
| 13 | + [Union[NoArgsNoReturnFuncT, NoArgsNoReturnAsyncFuncT]], NoArgsNoReturnAsyncFuncT |
| 14 | +] |
| 15 | + |
| 16 | + |
| 17 | +def repeat_every( # noqa: C901 |
| 18 | + *, |
| 19 | + seconds: float, |
| 20 | + wait_first: bool = False, |
| 21 | + logger: Optional[logging.Logger] = None, |
| 22 | + raise_exceptions: bool = False, |
| 23 | +) -> NoArgsNoReturnDecorator: |
| 24 | + """ |
| 25 | + This function returns a decorator that modifies a function so it is periodically re-executed after its first call. |
| 26 | + The function it decorates should accept no arguments and return nothing. If necessary, this can be accomplished |
| 27 | + by using `functools.partial` or otherwise wrapping the target function prior to decoration. |
| 28 | + Parameters |
| 29 | + ---------- |
| 30 | + seconds: float |
| 31 | + The number of seconds to wait between repeated calls |
| 32 | + wait_first: bool (default False) |
| 33 | + If True, the function will wait for a single period before the first call |
| 34 | + logger: Optional[logging.Logger] (default None) |
| 35 | + The logger to use to log any exceptions raised by calls to the decorated function. |
| 36 | + If not provided, exceptions will not be logged by this function (though they may be handled by the event loop). |
| 37 | + raise_exceptions: bool (default False) |
| 38 | + If True, errors raised by the decorated function will be raised to the event loop's exception handler. |
| 39 | + Note that if an error is raised, the repeated execution will stop. |
| 40 | + Otherwise, exceptions are just logged and the execution continues to repeat. |
| 41 | + See https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.set_exception_handler for more info. |
| 42 | + """ |
| 43 | + |
| 44 | + def decorator( |
| 45 | + func: Union[NoArgsNoReturnAsyncFuncT, NoArgsNoReturnFuncT] |
| 46 | + ) -> NoArgsNoReturnAsyncFuncT: |
| 47 | + """ |
| 48 | + Converts the decorated function into a repeated, periodically-called version of itself. |
| 49 | + """ |
| 50 | + is_coroutine = asyncio.iscoroutinefunction(func) |
| 51 | + |
| 52 | + @wraps(func) |
| 53 | + async def wrapped() -> None: |
| 54 | + async def loop() -> None: |
| 55 | + if wait_first: |
| 56 | + await asyncio.sleep(seconds) |
| 57 | + while True: |
| 58 | + try: |
| 59 | + if is_coroutine: |
| 60 | + await func() # type: ignore |
| 61 | + else: |
| 62 | + await run_in_threadpool(func) |
| 63 | + except Exception as exc: |
| 64 | + if logger is not None: |
| 65 | + formatted_exception = "".join( |
| 66 | + format_exception(type(exc), exc, exc.__traceback__) |
| 67 | + ) |
| 68 | + logger.error(formatted_exception) |
| 69 | + if raise_exceptions: |
| 70 | + raise exc |
| 71 | + await asyncio.sleep(seconds) |
| 72 | + |
| 73 | + ensure_future(loop()) |
| 74 | + |
| 75 | + return wrapped |
| 76 | + |
| 77 | + return decorator |
0 commit comments