python runtime_error ai_generated true

RuntimeError: Event loop is closed: call_soon() cannot be called

ID: python/asyncio-event-loop-call-later-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2025-08-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active
3.10 active

Root Cause

A callback is scheduled on an event loop that has already been closed, often after asyncio.run() finishes.

generic

中文

在已关闭的事件循环上调度回调,通常在 asyncio.run() 完成后发生。

Workarounds

  1. 85% success Ensure all callbacks are scheduled before the loop closes
    loop = asyncio.get_running_loop()
    loop.call_soon(some_callback)
    # ensure loop is still running
  2. 90% success Use asyncio.get_running_loop() to check if loop is active
    try:
        loop = asyncio.get_running_loop()
        loop.call_soon(callback)
    except RuntimeError:
        # loop not running, handle accordingly

Dead Ends

Common approaches that don't work:

  1. Using asyncio.get_event_loop() to get a new loop 60% fail

    If the loop is closed, get_event_loop() may raise an error or return a closed loop.

  2. Ignoring the error and assuming the callback ran 50% fail

    The callback never executes, leading to incomplete operations.