【12.2】task取消和子协程调用原理

task取消

 1 import asyncio
 2 import time
 3 
 4 
 5 async def get_html(sleep_time):
 6     print('waiting')
 7     await asyncio.sleep(sleep_time)
 8     print('done after {}s'.format(sleep_time))
 9 
10 
11 if __name__ == '__main__':
12     task1 = get_html(2)
13     task2 = get_html(3)
14     task3 = get_html(3)
15 
16     tasks = [task1, task2, task3]
17 
18     loop = asyncio.get_event_loop()
19 
20     try:
21         loop.run_until_complete(asyncio.gather(*tasks))
22     except KeyboardInterrupt as e:
23         # KeyboardInterrupt 是按Ctrl+C终止程序时抛出的异常
24         # 获取所有的task
25         all_tasks = asyncio.Task.all_tasks()
26         for task in all_tasks:
27             print('cancel task')
28             print(task.cancel())
29         loop.stop()
30         loop.run_forever()
31     finally:
32         loop.close()
waiting
waiting
waiting
cancel task
True
cancel task
True
cancel task
True

 

 

 

转载于:https://www.cnblogs.com/zydeboke/p/11369709.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值