# https://docs.python.org/zh-cn/3/library/asyncio-task.htmlimport asyncio
import time
from datetime import datetime
asyncdefsay_after(delay, what):await asyncio.sleep(delay)print(what)return what
# 原版,没有启动到异步asyncdefmain():# 0:00:03.002929print(f"started at {time.strftime('%X')}")await say_after(1,'hello')await say_after(2,'world')print(f"finished at {time.strftime('%X')}")# 异步1asyncdefmain():# 0:00:02.002949
task1 = asyncio.create_task(
say_after(1,'hello'))
task2 = asyncio.create_task(
say_after(2,'world'))print(f"started at {time.strftime('%X')}")# Wait until both tasks are completed (should take# around 2 seconds.)
res =[]
a =await task1
res.append(a)
a =await task2
res.append(a)print(f"finished at {time.strftime('%X')}")print(res)# 异步2asyncdefmain():# 0:00:02.002968print(f"started at {time.strftime('%X')}")
res =await asyncio.gather(
say_after(1,'hello'),
say_after(2,'world'))print(f"finished at {time.strftime('%X')}")print(res)
a = datetime.now()
asyncio.run(main())print(datetime.now()-a )