0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

asyincioで、時間待ち(sleep)や I/O 待ち処理をする。

0
Last updated at Posted at 2026-03-20

はじめに

asyncio は、Python で複数の処理を並行して進めたいときに使う非同期処理フレームワーク。時間待ち(sleep)や I/O 待ち(TCP/IP、UART、ファイル入力、input など)のように、待ち時間が発生する処理を効率よく扱えるため、イベント駆動型のプログラムで力を発揮する。

使い方

非同期処理を行う関数は async def で定義し、処理の途中で待ちが必要な箇所では await を使う。複数の処理を同時に走らせたい場合は asyncio.create_task()await asyncio.gather(task,,,)でタスクを登録し、asyncio.run() でイベントループを開始する。

  • 時間待ち(sleep)
    await asyncio.sleep(sec) を使うと、指定秒数だけ非同期で待つことができる。他のタスクはその間も動き続ける。
     
  • ブロッキング関数待ち(input や UART read など)
    await asyncio.to_thread(func, ...) を使うと、ブロッキングな処理を別スレッドで実行し、結果を非同期に受け取れる。
     
  • タスク間のデータ受け渡し(queue)
    asyncio.Queueを使いキューでタスク間のデータ受け渡しができる。データ詰込みはawait q.put(data)、取得はdata=await q.get()で行う。
sample.py
import asyncio
import datetime

async def loop_func(sec):
    while(1):
        await asyncio.sleep(sec)
        print(f'call:loop_func({sec}) {datetime.datetime.now()}')

async def input_func(q):
    while(1):
        data = await asyncio.to_thread(input, '文字を入力してください\n')
        await q.put(data)
        print(f'input_func({data})')

async def queue_func(q):
    while(1):
        data = await q.get()
        print(f'queue_func({data})')
        
async def main():
    
    q =asyncio.Queue()  # Queue準備

    task1 = asyncio.create_task(loop_func(1))   # 1秒ごとにコール
    task2 = asyncio.create_task(loop_func(5))   # 5秒ごとにコール
    task3 = asyncio.create_task(input_func(q))  # 入力待ち input()
    task4 = asyncio.create_task(queue_func(q))  # queueで起動
    
    await asyncio.gather(task1, task2, task3, task4)

if __name__ == "__main__":
    asyncio.run(main())


処理結果

文字を入力してください
call:loop_func(5) 2026-03-22 15:50:37.251756
call:loop_func(1) 2026-03-22 15:50:37.389352
call:loop_func(1) 2026-03-22 15:50:38.392777
call:loop_func(1) 2026-03-22 15:50:39.395538
call:loop_func(1) 2026-03-22 15:50:40.413335
call:loop_func(1) 2026-03-22 15:50:41.425841
call:loop_func(5) 2026-03-22 15:50:42.267601
call:loop_func(1) 2026-03-22 15:50:42.428112
call:loop_func(1) 2026-03-22 15:50:43.444979
call:loop_func(1) 2026-03-22 15:50:44.455328
eee
input_func(eee)
queue_func(eee)
文字を入力してください
call:loop_func(1) 2026-03-22 15:50:45.470275
call:loop_func(1) 2026-03-22 15:50:46.480706
call:loop_func(5) 2026-03-22 15:50:47.271585
call:loop_func(1) 2026-03-22 15:50:47.491766

参考記事

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?