diff background_loop.py @ 9:263ccb9e00df

port to asyncio and pdm
author drewp@bigasterisk.com
date Sun, 24 Apr 2022 14:56:36 -0700
parents a340a9bdaedb
children a1ed58edfccc
line wrap: on
line diff
--- a/background_loop.py	Wed Dec 22 20:36:21 2021 -0800
+++ b/background_loop.py	Sun Apr 24 14:56:36 2022 -0700
@@ -1,12 +1,16 @@
+# dev copy
+import asyncio
+import logging
 import time
 import traceback
-import logging
-from typing import Callable
-from prometheus_client import Gauge
+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:
@@ -21,24 +25,31 @@
         time.sleep(sleep_period)
 
 
-def loop_forever_async(func: Callable[[bool], None], sleep_period: float,
-                       up_metric: Gauge):
+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
     """
-    from twisted.internet import reactor
-    first_run = True
+    @call_metric.time()
+    async def call_func(first_run):
+        if asyncio.iscoroutinefunction(func):
+            await func(first_run)
+        else:
+            func(first_run)
 
-    def step():
-        nonlocal first_run
+    first_run = True
+    while True:
         try:
-            func(first_run)
+            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)
-        reactor.callLater(sleep_period, step)
-
-    step()
\ No newline at end of file
+            # todo: something that reveals error ratio
+        await asyncio.sleep(sleep_period)