Hello World

This is a series of examples showing the basics of how to write coroutines and schedule them in the asyncio event loop.

Simple coroutine

This example uses the asyncio.BaseEventLoop.run_until_complete() method to schedule a simple function that will wait one second, print hello and then finish.

Because it is launched with run_until_complete(), the event loop itself will terminate once the coroutine is completed.

import asyncio

async def say(what, when):
    await asyncio.sleep(when)
    print(what)

loop = asyncio.get_event_loop()
loop.run_until_complete(say('hello world', 1))
loop.close()

Creating tasks

This second example shows how you can schedule multiple coroutines in the event loop, and then run the event loop.

Notice that this example will print second_hello before first_hello, as the first task scheduled waits longer that the second one before printing.

Also note that this example will never terminate, as the loop is asked to run_forever.

import asyncio

async def say(what, when):
    await asyncio.sleep(when)
    print(what)


loop = asyncio.get_event_loop()

loop.create_task(say('first hello', 2))
loop.create_task(say('second hello', 1))

loop.run_forever()
loop.close()

Stopping the loop

This third example adds another task that will stop the event loop before all scheduled tasks could execute, which results in a warning.

import asyncio

async def say(what, when):
    await asyncio.sleep(when)
    print(what)

async def stop_after(loop, when):
    await asyncio.sleep(when)
    loop.stop()


loop = asyncio.get_event_loop()

loop.create_task(say('first hello', 2))
loop.create_task(say('second hello', 1))
loop.create_task(say('third hello', 4))
loop.create_task(stop_after(loop, 3))

loop.run_forever()
loop.close()

Warning:

Task was destroyed but it is pending!
task: <Task pending coro=<say() done, defined at examples/loop_stop.py:3>
wait_for=<Future pending cb=[Task._wakeup()]>>