diff --git a/api/common/__init__.py b/api/common/__init__.py index 92e37f9..a9044e1 100644 --- a/api/common/__init__.py +++ b/api/common/__init__.py @@ -1,5 +1,5 @@ from .decorators import data_decorator, router_decorator, async_router_decorator, name_to_fns_map from .siibra_api_typing import ROLE_TYPE -from .logger import logger, access_logger +from .logger import logger as general_logger, access_logger from .exceptions import * from .storage import get_filename diff --git a/api/common/timer.py b/api/common/timer.py index aa51513..9eb039c 100644 --- a/api/common/timer.py +++ b/api/common/timer.py @@ -1,4 +1,5 @@ from threading import Timer +from typing import List, Callable class RepeatTimer(Timer): """RepeatTimer @@ -8,3 +9,42 @@ class RepeatTimer(Timer): def run(self): while not self.finished.wait(self.interval): self.function(*self.args, **self.kwargs) + +class Cron: + def __init__(self) -> None: + self._minutely_fns: List[Callable] = [] + self._ten_minutely_fns: List[Callable] = [] + + self._timers: List[RepeatTimer] = [ + RepeatTimer(60, self._run_minutely), + RepeatTimer(600, self._run_ten_minutely) + ] + + def _run_minutely(self): + for fn in self._minutely_fns: + fn() + + def _run_ten_minutely(self): + for fn in self._ten_minutely_fns: + fn() + + def minutely(self, fn: Callable): + self._minutely_fns.append(fn) + return fn + + def ten_minutely(self, fn: Callable): + self._ten_minutely_fns.append(fn) + return fn + + def run_all(self): + self._run_ten_minutely() + self._run_minutely() + + def start(self): + for timer in self._timers: + timer.start() + + def stop(self): + """On terminate""" + for timer in self._timers: + timer.cancel()