comparison 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
comparison
equal deleted inserted replaced
-1:000000000000 0:a340a9bdaedb
1 import time
2 import traceback
3 import logging
4 from typing import Callable
5 from prometheus_client import Gauge
6
7 log = logging.getLogger()
8
9
10 def loop_forever_sync(func, sleep_period, up_metric):
11 first_run = True
12 while True:
13 try:
14 func(first_run)
15 up_metric.set(1)
16 first_run = False
17 except Exception as ex:
18 log.error(ex)
19 traceback.print_exc()
20 up_metric.set(0)
21 time.sleep(sleep_period)
22
23
24 def loop_forever_async(func: Callable[[bool], None], sleep_period: float,
25 up_metric: Gauge):
26 """
27 sleep_period is the sleep time after however long func takes to run
28 """
29 from twisted.internet import reactor
30 first_run = True
31
32 def step():
33 nonlocal first_run
34 try:
35 func(first_run)
36 up_metric.set(1)
37 first_run = False
38 except Exception as ex:
39 log.error(ex)
40 traceback.print_exc()
41 up_metric.set(0)
42 reactor.callLater(sleep_period, step)
43
44 step()