Home [Go] Golangでsleepする方法
Post
Cancel

[Go] Golangでsleepする方法

[Go] Golangでsleepする方法


Go言語でプログラムの実行を一時停止したり遅延させたい場合、timeパッケージのSleep関数を使用できます。この記事では、Goでsleepを使用する様々な方法を学びます。

基本的な使用方法

Goでsleepを使用するには、timeパッケージをインポートしてtime.Sleep()関数を呼び出します。

1
2
3
4
5
6
7
8
9
10
11
12
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("開始")
    time.Sleep(2 * time.Second)
    fmt.Println("2秒後")
}

time.Sleep()time.Duration型を引数として受け取ります。上記の例では、2 * time.Secondで2秒間待機します。

様々な時間単位

Goのtimeパッケージは様々な時間単位を提供します:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("開始")
    
    // ミリ秒単位
    time.Sleep(500 * time.Millisecond)
    fmt.Println("500ミリ秒後")
    
    // 秒単位
    time.Sleep(2 * time.Second)
    fmt.Println("2秒後")
    
    // 分単位
    time.Sleep(1 * time.Minute)
    fmt.Println("1分後")
    
    // 時間単位
    time.Sleep(1 * time.Hour)
    fmt.Println("1時間後")
}

使用可能な時間単位

単位説明
time.Nanosecondナノ秒 (1ns)
time.Microsecondマイクロ秒 (1µs)
time.Millisecondミリ秒 (1ms)
time.Second秒 (1s)
time.Minute分 (1m)
time.Hour時間 (1h)

実用的な例

1. 繰り返し作業の間に待機

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
    "fmt"
    "time"
)

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Printf("作業 %d 実行中...\n", i)
        time.Sleep(1 * time.Second)
    }
    fmt.Println("すべての作業完了")
}

2. API呼び出し間の遅延

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import (
    "fmt"
    "time"
)

func callAPI() {
    fmt.Println("API呼び出し中...")
    // API呼び出しロジック
}

func main() {
    for i := 0; i < 3; i++ {
        callAPI()
        // API呼び出し間に2秒待機(レート制限)
        time.Sleep(2 * time.Second)
    }
}

3. ゴルーチンと一緒に使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
    "fmt"
    "time"
)

func worker(id int) {
    for i := 0; i < 3; i++ {
        fmt.Printf("Worker %d: 作業 %d\n", id, i)
        time.Sleep(1 * time.Second)
    }
}

func main() {
    // 複数のゴルーチンを実行
    go worker(1)
    go worker(2)
    
    // メインゴルーチンが終了しないように待機
    time.Sleep(5 * time.Second)
    fmt.Println("すべての作業完了")
}

注意事項

  • time.Sleep()は現在のゴルーチンをブロックします。他のゴルーチンは引き続き実行されます。
  • 正確な時間を保証しません。システムスケジューラによって実際の待機時間が若干異なる場合があります。
  • 非常に短い時間(ナノ秒単位)のsleepは精度が低下する可能性があります。

time.After()との違い

time.Sleep()は指定された時間の間ブロックしますが、time.After()はチャネルを返して非同期に使用できます:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("開始")
    
    // time.Sleep() - ブロッキング
    time.Sleep(2 * time.Second)
    fmt.Println("2秒後 (Sleep)")
    
    // time.After() - ノンブロッキング(チャネル使用)
    <-time.After(2 * time.Second)
    fmt.Println("2秒後 (After)")
}

この記事がGoでsleepを使用する方法を理解するのに役立つことを願っています!

This post is licensed under CC BY 4.0 by the author.

Elasticsearchで特定の時間範囲のデータを検索・削除するクエリコマンド

-