sleep方法
阻塞一段時間,
如果傳入了result,那麼將會把這個結果傳遞給調用者。
sleep常常用來阻塞當前的task
,然後讓其他的task執行----禮讓。
然後loop參數是不建議傳入的,後面這個參數也會被刪除
async def sleep(delay, result=None, *, loop=None):
"""Coroutine that completes after a given time (in seconds)."""
if delay <= 0:
await __sleep0()
return result
if loop is None:
loop = events.get_running_loop()
else:
warnings.warn("The loop argument is deprecated and scheduled for "
"removal in Python 3.10.",
DeprecationWarning, stacklevel=2)
future = loop.create_future()
h = loop.call_later(delay,
futures._set_result_unless_cancelled,
future, result)
try:
return await future
finally:
h.cancel()
演示一個按秒提示的時鐘
import asyncio
import datetime
async def display_date():
loop = asyncio.get_running_loop()
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now(),end='\r')
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(1)
asyncio.run(display_date())
上面的演示結果就是不斷的更新時間,按照秒計數。