🐈

【Go】contextとtime.Afterを使用した待機処理

に公開
2025/08/27

概要

contextとtime.Afterを使用した待機処理の実装を、time.Sleepを使用した実装と比較して記載します。

単純な書き方の比較

1秒待機するという処理を、time.Sleepとtime.Afterのそれぞれで書いた単純な例を次に示します。

# 実行結果
time.After: 開始
time.Sleep: 開始
time.Sleep: 完了
time.After: 完了
package main

import (
	"fmt"
	"time"
)

func main() {
	done := make(chan string, 2)

	go func() {
		fmt.Println("time.Sleep: 開始")
		time.Sleep(1 * time.Second)
		done <- "time.Sleep: 完了"
	}()

	go func() {
		fmt.Println("time.After: 開始")
		select {
		case <-time.After(1 * time.Second):
			done <- "time.After: 完了"
		}
	}()

	fmt.Println(<-done)
	fmt.Println(<-done)
}

contextのキャンセル

time.Sleepを使用した場合、処理を即時に中断できない

次のtime.Sleepを使用した例では、1秒後にcontextのキャンセルが実行されますが、time.Sleepによってブロックされるため、待機時間の5秒が経過するまで処理が中断されません。

次の例ではerrgroupを使用しています。
https://pkg.go.dev/golang.org/x/sync/errgroup

# 実行結果
1秒後にキャンセル
5.001178875s 経過後にキャンセルを検出: context canceled
package main

import (
	"context"
	"fmt"
	"time"

	"golang.org/x/sync/errgroup"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	eg, ctx := errgroup.WithContext(ctx)

	startTime := time.Now()

	eg.Go(func() error {
		// 5秒間待機
		time.Sleep(5 * time.Second)

		if ctx.Err() != nil {
			fmt.Printf("%v 経過後にキャンセルを検出: %s\n", time.Since(startTime), ctx.Err().Error())
			return ctx.Err()
		}

		return nil
	})

	// 1秒後にキャンセル
	go func() {
		time.Sleep(1 * time.Second)
		fmt.Println("1秒後にキャンセル")
		cancel()
	}()


	if err := eg.Wait(); err != nil {
		// do something
	}
}

time.Afterを使用した場合、処理を即時に中断できる

time.Afterでは、キャンセルの通知を即座に受信し、処理を終了できます。

# 実行結果
1秒後にキャンセル
1.001311375s 経過後にキャンセルを検出: context canceled
1.001409833s 経過後に終了
package main

import (
	"context"
	"fmt"
	"time"

	"golang.org/x/sync/errgroup"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	eg, ctx := errgroup.WithContext(ctx)

	startTime := time.Now()

	eg.Go(func() error {
		select {
		case <-time.After(5 * time.Second):
			return nil
		case <-ctx.Done():
			fmt.Printf("%v 経過後にキャンセルを検出: %s\n", time.Since(startTime), ctx.Err().Error())
			return ctx.Err()
		}
	})

	// 1秒後にキャンセル
	go func() {
		time.Sleep(1 * time.Second)
		fmt.Println("1秒後にキャンセル")
		cancel()
	}()

	if err := eg.Wait(); err != nil {
		// do something
	}

	fmt.Printf("%v 経過後に終了\n", time.Since(startTime))
}

contextのタイムアウト

time.Sleepを使用した場合、タイムアウト後も処理が実行される

つぎの例では、2秒のタイムアウトを持つcontextを用意し、Goroutineの中で3秒のtime.Sleepを実行しています。

実行結果は以下のようになり、contextのタイムアウト後もGoroutine内部の処理が中断せずに実行されています。

# 実行結果
goroutine 開始
[2s] タイムアウト検出: context deadline exceeded
[3s] タイムアウト後も実行される
送信失敗: 受信者なし
package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	// 2秒のタイムアウトを持つcontextを作成
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	startTime := time.Now()

	// time.Sleepを使用
	result := make(chan string)
	go func() {
		fmt.Printf("goroutine 開始\n")

		time.Sleep(3 * time.Second)

		fmt.Printf("[%v] タイムアウト後も実行される\n", time.Since(startTime).Round(time.Second))

		// channelに送信
		select {
		case result <- "処理完了":
			fmt.Println("送信成功")
		default:
			fmt.Println("送信失敗: 受信者なし")
		}
	}()

	// goroutineのタイムアウトを待つ
	select {
	case res := <-result:
		fmt.Printf("[%v] 結果受信: %s\n", time.Since(startTime).Round(time.Second), res)
	case <-ctx.Done():
		fmt.Printf("[%v] タイムアウト検出: %v\n", time.Since(startTime).Round(time.Second), ctx.Err())
	}

	// goroutineが終了するまでの秒数を待機
	time.Sleep(2 * time.Second)
}

time.Afterを使用した場合、処理が中断される

一方で、time.Afterを使用した場合は、つぎのようにタイムアウトが検出されたときに、Goroutine内部でctx.Doneのキャンセル処理が実行されるため、処理が中断されています。

# 実行結果
goroutine 開始
[2s] タイムアウト検出: context deadline exceeded
[2s] Goroutineでタイムアウト検出: context deadline exceeded
package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	startTime := time.Now()
	result := make(chan string)

	go func() {
		fmt.Printf("goroutine 開始\n")

		select {
		case <-time.After(3 * time.Second):
			fmt.Printf("[%v] 処理完了\n", time.Since(startTime).Round(time.Second))
			result <- "処理完了"
		case <-ctx.Done():
			fmt.Printf("[%v] Goroutineでタイムアウト検出: %v\n", time.Since(startTime).Round(time.Second), ctx.Err())
			return
		}

		// ctx.Done()でキャンセルが検出されるため、このメッセージは表示されない
		fmt.Println("キャンセル時にここには到達しない")
	}()

	select {
	case res := <-result:
		fmt.Printf("[%v] 結果受信: %s\n", time.Since(startTime).Round(time.Second), res)
	case <-ctx.Done():
		fmt.Printf("[%v] タイムアウト検出: %v\n", time.Since(startTime).Round(time.Second), ctx.Err())
	}
}

Discussion