[12.2] to cancel and sub-task coroutine call principle

task Cancel

 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     = get_html Task3 (. 3 )
 15  
16      Tasks = [Task1, Task2, Task3]
 . 17  
18 is      Loop = asyncio.get_event_loop ()
 . 19  
20 is      the try :
 21 is          loop.run_until_complete (asyncio.gather (* Tasks))
 22 is      the except the KeyboardInterrupt AS E:
 23 is          # the KeyboardInterrupt is press Ctrl + C in case of an abnormal termination of the program 
24          # acquired all Task 
25          all_tasks = asyncio.Task.all_tasks ()
 26 is          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

 

 

 

Guess you like

Origin www.cnblogs.com/zydeboke/p/11369709.html