Code/Recipes/Async

From Polytech Center Barcelona
Jump to: navigation, search
import asyncio

async def foo():
    print("Foo started!")
    await asyncio.sleep(2)
    print("Foo done!")

async def bar():
    print("Bar started!")
    await asyncio.sleep(3)
    print("Bar done!")

async def main():
    print("Main started!")
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(bar())
    await asyncio.sleep(1)
    print("Main finished!")
    # Wait for tasks to finish
    await task1
    await task2
    print("Everything finished.")

asyncio.run(main())