Asyncio python

From Teknologisk videncenter
Jump to: navigation, search

For a primer see Yield python

await vs. asyncio.create()

import asyncio
import time

async def fetch_data(url):
    # Simulate a long-running network request
    await asyncio.sleep(2)  # Wait for 2 seconds
    print(f"Data fetched from {url}")

async def main():
    task1 = asyncio.create_task(fetch_data("https://example.com"))
    task2 = asyncio.create_task(fetch_data("https://another.example.com"))

    await task1
    await task2

if __name__ == "__main__":
    asyncio.run(main())

Links