Skip to content

Commit e1de106

Browse files
committed
Use get_running_loop() instead of str cmp to check for a running event loop
Signed-off-by: Mathias L. Baumann <[email protected]>
1 parent b16b037 commit e1de106

File tree

2 files changed

+18
-18
lines changed

2 files changed

+18
-18
lines changed

src/frequenz/sdk/_internal/_asyncio.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import asyncio
88
import logging
9+
import sys
910
from abc import ABC
1011
from datetime import timedelta
1112
from typing import Any, Callable, Coroutine
@@ -32,6 +33,15 @@ async def cancel_and_await(task: asyncio.Task[Any]) -> None:
3233
pass
3334

3435

36+
def is_loop_running() -> bool:
37+
"""Check if the event loop is running."""
38+
try:
39+
asyncio.get_running_loop()
40+
return True
41+
except RuntimeError:
42+
return False
43+
44+
3545
async def run_forever(
3646
async_callable: Callable[[], Coroutine[Any, Any, None]],
3747
interval: timedelta = timedelta(seconds=1),
@@ -46,20 +56,10 @@ async def run_forever(
4656
while True:
4757
try:
4858
await async_callable()
49-
except RuntimeError as exc:
50-
if "no running event loop" in str(exc):
51-
_logger.exception(
52-
"Something went wrong, no running event loop, skipping execution of %s",
53-
async_callable.__name__,
54-
)
55-
return
5659
except Exception: # pylint: disable=broad-except
57-
if not asyncio.get_event_loop().is_running():
58-
_logger.exception(
59-
"Something went wrong, no running event loop, skipping execution of %s",
60-
async_callable.__name__,
61-
)
62-
return
60+
if not is_loop_running():
61+
_logger.exception("There is no running event loop, aborting...")
62+
sys.exit(-1)
6363
_logger.exception("Restarting after exception")
6464
await asyncio.sleep(interval_s)
6565

src/frequenz/sdk/actor/_actor.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import logging
99
from datetime import timedelta
1010

11+
from .._internal._asyncio import is_loop_running
1112
from ._background_service import BackgroundService
1213

1314
_logger = logging.getLogger(__name__)
@@ -104,16 +105,15 @@ async def _run_loop(self) -> None:
104105
except asyncio.CancelledError:
105106
_logger.info("Actor %s: Cancelled.", self)
106107
raise
107-
except Exception as exc: # pylint: disable=broad-except
108-
if isinstance(exc, RuntimeError) and "no running event loop" in str(
109-
exc
110-
):
108+
except Exception: # pylint: disable=broad-except
109+
if not is_loop_running():
111110
_logger.exception(
112111
"Something went wrong, no running event loop,"
113112
" not trying to restart %s again.",
114113
self,
115114
)
116-
break
115+
raise
116+
117117
if self._is_cancelled:
118118
# If actor was cancelled, but any tasks have failed with an exception
119119
# other than asyncio.CancelledError, those exceptions are combined

0 commit comments

Comments
 (0)