Created
May 20, 2021 13:13
-
-
Save rogerwelin/b644c046730158cd24e45dadc0396dea to your computer and use it in GitHub Desktop.
context sigint
This file contains 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
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"os" | |
"os/signal" | |
"time" | |
) | |
func doSomethingAwesome(ctx context.Context, msg string) { | |
for { | |
select { | |
case <-ctx.Done(): | |
// run cleanup logic here | |
log.Println(ctx.Err()) | |
fmt.Println("shutting down gracefully - running cleanup") | |
return | |
default: | |
time.Sleep(200 * time.Millisecond) | |
fmt.Print(".") | |
} | |
} | |
} | |
func main() { | |
// create context that listens for SIGINT from OS | |
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) | |
defer cancel() | |
doSomethingAwesome(ctx, "ello") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment