Last active
August 6, 2021 20:20
-
-
Save anyu/5a1ca2748a15aecb270b8642604db7ea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Go1.16+'s signal.NotifyContext to concisely handle graceful shutdowns on OS interrupts. | |
// Simple example from original submitter: https://henvic.dev/posts/signal-notify-context/ | |
func main() { | |
// Pass a context with a timeout to tell a blocking function that it | |
// should abandon its work after the timeout elapses. | |
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) | |
defer stop() | |
select { // blocks until | |
case <-time.After(10 * time.Second): | |
fmt.Println("missed signal") | |
case <-ctx.Done(): | |
stop() | |
fmt.Println("signal received") | |
} | |
} | |
// <Go1.16's approach | |
func main() { | |
ctx, cncl := context.WithCancel(context.Background()) | |
defer cncl() | |
signals := make(chan os.Signal, 1) // channel to intercept OS cmds | |
signal.Notify(signals, os.Interrupt) | |
go func() { | |
select { | |
case <-signals: | |
cncl() | |
case <-ctx.Done(): | |
} | |
}() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment