1. wait, 等待某某執行完成以后才執行下一步
FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
import asyncio import time async def get_html(term): print("start get url") await asyncio.sleep(term) print("end get url") if __name__ == '__main__': group1 = [get_html(i) for i in range(10)] loop = asyncio.get_event_loop() import concurrent.futures loop.run_until_complete(asyncio.wait(group1, return_when=concurrent.futures.FIRST_COMPLETED)) print(1)
2. gather 比wait更加高級,可以將任務分組,並且取消掉,取消時,必須設置 return_exception為True,不然會拋異常
import asyncio import time async def get_html(url): print("start get url") await asyncio.sleep(2) print("end get url") if __name__ == "__main__": start_time = time.time() loop = asyncio.get_event_loop() #gather和wait的區別 #gather更加high-level group1 = [get_html("http://projectsedu.com") for i in range(2)] # 分組 group2 = [get_html("http://www.imooc.com") for i in range(2)] group1 = asyncio.gather(*group1) group2 = asyncio.gather(*group2) group2.cancel() loop.run_until_complete(asyncio.gather(group1, group2, return_exceptions=True)) print(time.time() - start_time)