タスクがキャンセル
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()
待って 待って 待っている タスクのキャンセル 真は タスク取り消し 真の タスクをキャンセル トゥルー