Mercurial > code > home > repos > background_loop
changeset 0:a340a9bdaedb
factor this out from wherever it was
author | drewp@bigasterisk.com |
---|---|
date | Wed, 22 Dec 2021 19:23:34 -0800 |
parents | |
children | 10defe60b8a5 |
files | background_loop.py setup.py tasks.py |
diffstat | 3 files changed, 68 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/background_loop.py Wed Dec 22 19:23:34 2021 -0800 @@ -0,0 +1,44 @@ +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() \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/setup.py Wed Dec 22 19:23:34 2021 -0800 @@ -0,0 +1,15 @@ +from setuptools import setup + +setup( + name='background_loop', + version='0.0.0', + packages=['background_loop'], + package_dir={'background_loop': ''}, + install_requires=[ + 'prometheus_client', + 'twisted', + ], + url='https://projects.bigasterisk.com/background_loop/background_loop-0.0.0.tar.gz', + author='Drew Perttula', + author_email='drewp@bigasterisk.com', +)