2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python3.10で非同期処理を完了を待たないで実行

Last updated at Posted at 2021-12-30

完了を待たないで実行(fire and forget)

run_in_executor()の引数は(executor, func, *args)になっているので、呼び出す関数を2番目の引数、呼び出す関数に渡す引数を3番目以降の可変長引数に渡します。

Python3.10以降では、asyncio.get_event_loop()をした際に実行中のイベントループがない場合はDeprecationWarningが出るのでasyncio.new_event_loop()を使いましょう。

import asyncio
import time

def func(sec: int):
    print("start")
    time.sleep(sec)  # 重い処理の代わり
    print("finish")

for i in range(10):
    print(i)
    if i == 3:
        asyncio.new_event_loop().run_in_executor(None, func, 3)
    time.sleep(1)
実行結果
0
1
2
3
start
4
5
finish
6
7
8
9

参考

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?