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秒,未能执行。
posted on 2018-03-19 10:55 北京涛子 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/liujitao79/p/8600660.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值