From f23d7f2e3717a3278eada368fa9866cbf4013d5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn-Michael=20Miehe?= <40151420+ldericher@users.noreply.github.com> Date: Fri, 1 Sep 2023 00:19:04 +0000 Subject: [PATCH] better timing with concurrency --- kiwi_simple_metrics/main.py | 49 ++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/kiwi_simple_metrics/main.py b/kiwi_simple_metrics/main.py index 64fc202..5bedeff 100644 --- a/kiwi_simple_metrics/main.py +++ b/kiwi_simple_metrics/main.py @@ -9,37 +9,40 @@ from . import metrics from .settings import SETTINGS -async def run_metrics() -> None: - while True: - interval = asyncio.sleep(SETTINGS.interval) +def handle_report() -> None: + # create single report from metrics + report = metrics.Report.summary( + metrics.cpu(), + metrics.memory(), + metrics.disk(), + ) - # create single report from metrics - report = metrics.Report.summary( - metrics.cpu(), - metrics.memory(), - metrics.disk(), + # maybe print this to stdout + if SETTINGS.log.enabled: + print(report) + + # maybe push this to a webhook + if (url := SETTINGS.webhook.get_url(failed=report.failed)) is not None: + requests.get( + url=str(url).format( + urllib.parse.quote_plus(report.result) + ), + verify=not SETTINGS.webhook.insecure, ) - # maybe print this to stdout - if SETTINGS.log.enabled: - print(report) - # maybe push this to a webhook - if (url := SETTINGS.webhook.get_url(failed=report.failed)) is not None: - requests.get( - url=str(url).format( - urllib.parse.quote_plus(report.result) - ), - verify=not SETTINGS.webhook.insecure, - ) +async def run_metrics() -> None: + loop = asyncio.get_running_loop() - await interval + while True: + await asyncio.gather( + asyncio.sleep(SETTINGS.interval), + loop.run_in_executor(None, handle_report), + ) def main() -> None: - loop = asyncio.get_event_loop() - loop.create_task(run_metrics()) - loop.run_forever() + asyncio.run(run_metrics()) if __name__ == "__main__":