linzhengen / tech-notes

My tech notes write in github issues🧲
1 stars 0 forks source link

[20210629] golang 1.16の `signal.NotifyContext`の体験は素晴らしい #119

Open linzhengen opened 3 years ago

linzhengen commented 3 years ago
package main

import (
    "context"
    "fmt"
    "os"
    "os/signal"
    "syscall"
    "time"
)

func main() {
    // signal監視とContextは一行で完結
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
    // signalキャッチしたときに、ctx.Doneが実行される
    defer stop()

    workLoop(ctx)
    fmt.Println("graceful shuwdown")
}

func workLoop(ctx context.Context) {
LOOP:
    for {
        select {
        case <-ctx.Done():
            // ループ終了
            break LOOP
        default:
            // ビジネスロジックはここ
            time.Sleep(time.Second * 10)
        }
    }
}