asyncio标准库1 Hello World

利用asyncio的event loop,编写和调度协程
coroutine [,kəuru:'ti:n] n. 协程

Simple coroutine(调用1个协程)

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))  # 使用run_until_complete()方法,在协程完成后中断event loop。
loop.close()

Creating tasks(调用多个协程)

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()  # 使用run_forever()方法,协程会一直运行,不会中断event loop
loop.close()

Stopping the loop

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()  # 中断event loop

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()
# out:
second hello
first hello
Task was destroyed but it is pending!
task: <Task pending coro=<say() done, defined at e03.py:5> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7fed59595a68>()]>>

# 在执行2个任务后,中断event loop,'third hello‘任务由于延迟时间4秒,未能执行。
原文地址:https://www.cnblogs.com/liujitao79/p/8600660.html