Working with the Event Loop

Starting and Stopping the Event Loop

The event loop is the core of Asyncio, managing the execution of asynchronous tasks. You start the event loop using or loop.run_until_complete(), and you can stop it using loop.stop(). It’s important to ensure that the event loop is properly closed after use to release resources.

import asyncio

async def main():
    print("Starting event loop")
    await asyncio.sleep(1)
    print("Stopping event loop")

loop = asyncio.get_event_loop()

Running Tasks in the Event Loop

Tasks are created from coroutines and scheduled to run in the event loop. You can create tasks using asyncio.create_task() or loop.create_task(), and the event loop manages their execution.

import asyncio

async def my_task(name):
    print(f"Task {name} started")
    await asyncio.sleep(2)
    print(f"Task {name} completed")

async def main():
    task1 = asyncio.create_task(my_task("A"))
    task2 = asyncio.create_task(my_task("B"))
    await task1
    await task2

Managing Multiple Event Loops

In most cases, a single event loop is sufficient for an application. However, advanced scenarios may require multiple event loops, which can be managed using asyncio.set_event_loop() and asyncio.new_event_loop(). It’s crucial to avoid running multiple event loops in the same thread to prevent conflicts and unexpected behavior.

import asyncio

async def task1():
    await asyncio.sleep(1)
    print("Task 1 completed")

async def task2():
    await asyncio.sleep(1)
    print("Task 2 completed")

loop1 = asyncio.new_event_loop()
loop2 = asyncio.new_event_loop()