python asyncio call_at call_later call_soon 完成阻塞Io

import asyncio
from concurrent.futures import ThreadPoolExecutor
import requests
def get_html(url):
    print(url)
    code=requests.get(url).status_code
    print(code)

if __name__=="__main__":
    urls=["http://www.baidu.com","http://www.sina.com.cn","http://www.163.com","http://www.qq.com"]
    loop=asyncio.get_event_loop()
    ##call_at  call_later call_soon
    # now=loop.time()
    # loop.call_at(now+1,get_html,"http://www.baidu.com")##1s后执行
    # loop.call_later(2,get_html,"http://www.sina.com.cn")##2s后执行
    # loop.call_soon(get_html,"http://www.163.com")##立即 最先执行
    # loop.run_forever()
    ##asyncio完成阻塞Io
    executor=ThreadPoolExecutor(3)
    tasks=[loop.run_in_executor(executor,get_html,url) for url in urls]
    loop.run_until_complete(asyncio.wait(tasks))

 

posted @ 2019-12-04 14:07  howhy  阅读(263)  评论(0)    收藏  举报