PYTHONWarningRuntime ErrorMay 30, 2026

Runtime Error

RuntimeError: Event loop is closed while an asynchronous task is still pending

What This Error Means

This error occurs when a Python async function or coroutine is still running when the event loop is closed, typically when a program exits or an exception is raised.

Why It Happens

This error happens when an asynchronous task is not properly awaited, or the event loop is not properly managed, leading to the event loop being closed before the task completes.

How to Fix It

  1. 1To fix this error, make sure to await all asynchronous tasks before closing the event loop. You can also use try/except blocks to catch any exceptions and properly clean up the event loop.

Example Code Solution

❌ Before (problematic code)
Python
async def my_task():
    while True:
        print('Running...')

async def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(my_task())
    # Close the event loop without awaiting my_task()
✅ After (fixed code)
Python
async def my_task():
    try:
        while True:
            print('Running...')
    finally:
        # Clean up the task
        pass

async def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(my_task())
    await asyncio.gather(my_task())
    # Close the event loop after awaiting my_task()

Fix for RuntimeError: Event loop is closed while an asynchronous task is still pending

Related PYTHON Errors

Related PYTHON Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error