task 是协程和 Future 的桥梁。
原因:
await asyncio.sleep(1) # 异步阻塞(等待另一个协程)
task = event_loop.create_task(task_func()) # 在全局轮训器加入协成,只有加入全局轮训器才能被监督执task.add_done_callback(callback) # 添加一个回调
event_loop = asyncio.get_event_loop() # 获取异步事件循环。
event_loop.run_until_complete(main(event_loop))# 用这个协程启动循环,协程返回时这个方法将停止循环。
event_loop.close() # 当事件循环关闭以后,所有没有执行完成的协成将全部关闭
# coding=utf-8
import time
import asyncio
from aiohttp import ClientSession
url = "https://docs.python.org/3/library/asyncio-task.html"
async def hello (url):
async with ClientSession() as session:
async with session.get(url) as response:
response = await response.read()
# print(response)
print('Hello World:%s' % time.ctime())
async def main (loop):
now = time.time()
tasks = []
for i in range(5):
task = asyncio.ensure_future(hello(url.format(i)))
tasks.append(task)
await asyncio.wait(tasks)
print("总用时", time.time() - now)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
# ------------------------------------------------
try:
# 用这个协程启动循环,协程返回时这个方法将停止循环。
loop.run_until_complete(main(loop))
finally:
loop.close()
输出:
Hello World:Wed Oct 9 13:30:15 2019
Hello World:Wed Oct 9 13:30:17 2019
Hello World:Wed Oct 9 13:30:17 2019
Hello World:Wed Oct 9 13:30:17 2019
Hello World:Wed Oct 9 13:30:18 2019
总用时 4.069105625152588