多任务+异步协程


import asyncio
import time
import aiohttp

class Start_task(object):

def __init__(self):
self.tasks = []
async def func(self):
'''协程任务'''
print("协程任务")

def callback(self):
'''回调函数'''
pass

def start_task(self):

loon = asyncio.get_event_loop()
loon.run_until_complete(asyncio.await(self.tasks))






import asyncio
from time import sleep
import time
#函数的定义
async def get_request(url):
print('正在请求:',url)
await asyncio.sleep(3)
print('请求结束:',url)
return 'bobo'

def parse(task):
print('i am task callback()!!!=----',task.result())


#创建3个协程对象
urls = [
'1.com','2.com','3.com'
]

start = time.time()
#任务列表:存储的是多个任务对象
tasks = []
for url in urls:
c = get_request(url)
task = asyncio.ensure_future(c)
#绑定回调
task.add_done_callback(parse)
tasks.append(task)

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

print('总耗时:',time.time()-start)
posted @ 2020-05-13 02:38  koala_dz  阅读(137)  评论(0编辑  收藏  举报