Mercurial > code > home > repos > background_loop
view background_loop.py @ 0:a340a9bdaedb
factor this out from wherever it was
author | drewp@bigasterisk.com |
---|---|
date | Wed, 22 Dec 2021 19:23:34 -0800 |
parents | |
children | 263ccb9e00df |
line wrap: on
line source
import time import traceback import logging from typing import Callable from prometheus_client import Gauge log = logging.getLogger() 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) def loop_forever_async(func: Callable[[bool], None], sleep_period: float, up_metric: Gauge): """ sleep_period is the sleep time after however long func takes to run """ from twisted.internet import reactor first_run = True def step(): nonlocal first_run 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) reactor.callLater(sleep_period, step) step()