最終更新:2021-08-13 (金) 13:55:27 (949d)
Python/イベントループ
頼まれた仕事を順番にどんどん処理していく
https://docs.python.org/ja/3/library/asyncio-eventloop.html
https://docs.python.org/ja/3.6/library/asyncio-eventloop.html
概要
- Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses.
メモ
- 普通はasyncio.runとかを使ってループとかには触らない
取得
asyncio.get_event_loop
- Get the current event loop.
asyncio.get_running_loop
- Return the running event loop in the current OS thread.
- Python 3.7~
asyncio.new_event_loop?
クラス
asyncio.AbstractEventLoop
- イベントループの抽象基底クラスです。
asyncio.BaseEventLoop?
メソッド
ループの実行・停止
loop.run_forever()
- stop() が呼ばれるまで実行します。
loop.run_until_complete(future)
- Future が完了するまで実行します。
- If the argument is a coroutine object it is implicitly scheduled to run as a asyncio.Task.
- 引数がコルーチンオブジェクトの場合、asyncio.ensure_future() でラップされます。
loop.stop?()
- 実行中のイベントループを停止します
- run_forever() は次の適当な時に終了します
loop.close?()
- イベントループを閉じます
- ループは実行中ではいけません。保留中のコールバックは失われます。
- これはキューをクリアし実行者をシャットダウンしますが、実行者の終了を待ちません。
コールバックのスケジューリング
loop.call_soon?
loop.call_soon_threadsafe?
コールバックの遅延スケジューリング
loop.call_later?
- 引数delayに遅らせたい時間(秒)を設定
loop.call_at?
loop.time?
生成
asyncio.Future loop.create_future? Create an asyncio.Future object attached to the event loop. This is the preferred way to create Futures in asyncio asyncio.Task loop.create_task Schedule the execution of a コルーチン. asyncio.Task asyncio.create_task Wrap the coro coroutine into a Task and schedule its execution
ネットワーク
loo.create_connection?
loop.create_server
動かし方
asyncio.run(coro)
loop.run_forever
loop.run_until_complete
- 指定した awaitable なオブジェクトが終了するまで実行