asyncio.shield的使用

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())

 

发表于 2023年07月14日 16:02   评论:0   阅读:1348  



回到顶部

首页 | 关于我 | 关于本站 | 站内留言 | rss
python logo   django logo   tornado logo