91. Event Loop in asyncio

Here are 10 Python code snippets demonstrating how to work with the event loop in Python's asyncio for running asynchronous tasks:


1. Basic Event Loop Execution

import asyncio

async def greet():
    print("Hello, World!")
    await asyncio.sleep(1)
    print("Goodbye, World!")

asyncio.run(greet())

This creates a coroutine greet() and runs it using asyncio.run().


2. Running Multiple Coroutines

import asyncio

async def task1():
    print("Task 1 starting...")
    await asyncio.sleep(2)
    print("Task 1 done.")

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

async def main():
    await asyncio.gather(task1(), task2())

asyncio.run(main())

asyncio.gather() runs multiple coroutines concurrently.


3. Using asyncio.create_task

asyncio.create_task() schedules coroutines to run concurrently.


4. Running Tasks Sequentially

Tasks are executed one after another using await.


5. Using asyncio.sleep for Delays

This demonstrates using asyncio.sleep() to create a delay in an asynchronous function.


6. Handling Exceptions in Coroutines

Exceptions in coroutines can be caught and handled with standard try/except blocks.


7. Running Tasks with Timeouts

asyncio.wait_for() allows setting a timeout for a coroutine.


8. Using asyncio.run_until_complete

run_until_complete() runs the event loop until the coroutine is done. Note: asyncio.run() is preferred in most cases.


9. Using asyncio.as_completed

asyncio.as_completed() yields results of tasks as they complete.


10. Running Background Tasks

This demonstrates running a long-running background task that can be canceled.


These snippets cover a variety of scenarios for running and managing asynchronous tasks using the asyncio event loop in Python.

Last updated