Event Loop is a loop for processing asynchronous tasks.
1import asyncio23# Tasks4async def task1():5 await asyncio.sleep(2)6 return "Task 1"78async def task2():9 await asyncio.sleep(1)10 return "Task 2"1112# Parallel execution13async def main():14 # gather — all tasks15 results = await asyncio.gather(task1(), task2())16 print(results) # ["Task 1", "Task 2"]1718 # wait_for — with timeout19 try:20 result = await asyncio.wait_for(task1(), timeout=1.0)21 except asyncio.TimeoutError:22 print("Timeout!")2324 # as_completed — as they complete25 tasks = [task1(), task2()]26 for coro in asyncio.as_completed(tasks):27 result = await coro28 print(f"Completed: {result}")2930asyncio.run(main())
Loop methods: