Asyncio python

From Teknologisk videncenter
Revision as of 09:03, 5 October 2024 by Heth (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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