Mercurial > code > home > repos > background_loop
view background_loop.py @ 14:64eddfd8b17c 1.3.0
release 1.3.0
author | drewp@bigasterisk.com |
---|---|
date | Sun, 24 Apr 2022 15:08:00 -0700 |
parents | 263ccb9e00df |
children | a1ed58edfccc |
line wrap: on
line source
# dev copy import asyncio import logging import time import traceback from typing import Awaitable, Callable from prometheus_client import Gauge, Summary log = logging.getLogger() # throw this away (when net_routes is rewritten) def loop_forever_sync(func, sleep_period, up_metric): first_run = True while True: try: func(first_run) up_metric.set(1) first_run = False except Exception as ex: log.error(ex) traceback.print_exc() up_metric.set(0) time.sleep(sleep_period) async def loop_forever( func: Callable[[bool], Awaitable[None]], sleep_period: float, up_metric: Gauge, call_metric: Summary, ): """ sleep_period is the sleep time after however long func takes to run """ @call_metric.time() async def call_func(first_run): if asyncio.iscoroutinefunction(func): await func(first_run) else: func(first_run) first_run = True while True: try: await call_func(first_run) up_metric.set(1) first_run = False except Exception as ex: log.error(ex) traceback.print_exc() up_metric.set(0) # todo: something that reveals error ratio await asyncio.sleep(sleep_period)