python的asyncio.wait_for可以用于设置等待异步任务的超时时间,参数可以是任何awaitable的对象。这个时候对象是否需要使用asyncio.shield()包起来呢?当超时抛出asyncio.TimeoutError时,默认会cancel掉等待的对象,如果不希望这一默认行为,就需要使用asyncio.shield()包起来。
举例一:
import asyncio
async def eternity():
# Sleep for one hour
await asyncio.sleep(6)
print('yay!')
async def main():
# Wait for at most 1 second
try:
#await asyncio.wait_for(eternity(), timeout=1.0)
#只会输出timeout!
await asyncio.wait_for(asyncio.shield(eternity()), timeout=1.0)
#会输出timeout!和yay!
except asyncio.TimeoutError:
print('timeout!')
await asyncio.sleep(7)
asyncio.run(main())
举例二:
import asyncio
def eternity():
fu = asyncio.Future()
# Sleep for one hour
asyncio.get_running_loop().call_later(6, lambda: fu.set_result('yay!'))
return fu
async def main():
# Wait for at most 1 second
fu = eternity()
try:
#await asyncio.wait_for(fu, timeout=1.0)
#只会输出timeout!
await asyncio.wait_for(asyncio.shield(fu), timeout=1.0)
#会输出timeout!和yay!
except asyncio.TimeoutError:
print('timeout!')
await asyncio.sleep(7)
print(fu.result())
asyncio.run(main())