取消协程执行

取消协程执行

# 官网:https://docs.python.org/zh-cn/3/library/asyncio-task.html?highlight=cancel#asyncio.Task.cancel

import asyncio


# 取消协程执行
async def cancel_me():
    print('cancel_me(): before sleep')

    try:
        # Wait for 1 hour
        await asyncio.sleep(3600)
    except asyncio.CancelledError:
        print('cancel_me(): cancel sleep')
        raise
    finally:
        print('cancel_me(): after sleep')


async def main():
    # Create a "cancel_me" Task
    task = asyncio.create_task(cancel_me())

    # Wait for 1 second
    await asyncio.sleep(1)

    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("main(): cancel_me is cancelled now")


# Expected output:
#
#     cancel_me(): before sleep
#     cancel_me(): cancel sleep
#     cancel_me(): after sleep
#     main(): cancel_me is cancelled now

if __name__ == '__main__':
    asyncio.run(main())

 

posted @ 2022-02-26 11:37  LiShiChao  阅读(85)  评论(0)    收藏  举报