[12.2]キャンセルすると、サブタスクコルーチンの呼び出し原理

タスクがキャンセル

1  インポートasyncio
 2  インポート時間
 3  
4  
5非同期デフget_html(SLEEP_TIME):
 6      プリント' 待機' 7      asyncio.sleep(SLEEP_TIME)待つ
 8      プリント' {}の後に行わ' .format(SLEEP_TIME))
 9  
10  
11  もし __name__ == ' __main__ ' 12      TASK1 = get_html(2 13      タスク2 = get_html(3 14     (3 = get_htmlタスク3 15の 
16      タスク= [タスク1、タスク2、タスク3]
 17。 
18である      ループ= asyncio.get_event_loop()
 19。 
20      試み21である          loop.run_until_complete(asyncio.gather(* 手順))
 22である     以外はE AS KeyboardInterrupt:
 23であります         KeyboardInterruptは、Ctrl + Cを押しているプログラムの異常終了の場合には
24          すべてのタスク取得
25          all_tasks =のasyncio.Task.all_tasks()は
 26である         ため、タスクall_tasks:
 27              プリントタスクをキャンセル' 28              プリント(task.cancel())
 29          loop.stop()
 30          loop.run_forever()
 31      最終的に32          loop.close()
待って
待って
待っている
タスクのキャンセル
真は
タスク取り消し
真の
タスクをキャンセル
トゥルー

 

 

 

おすすめ

転載: www.cnblogs.com/zydeboke/p/11369709.html