Last active
September 23, 2019 07:05
-
-
Save maelvls/1df2d49f017ca0e65d1e7fd83f81d28e to your computer and use it in GitHub Desktop.
Graceful shutdown with Context + channels (https://play.golang.org/p/ZBxNMddpbj2)
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
// The point of this snippet is to showcase how to handle gracefully any incoming | |
// SIGINT (manual ctrl-c) or SIGTERM (process is killed) for a long-running task | |
// such as a server. | |
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
func LongRunning(ctx context.Context) error { | |
timeout := time.After(1 * time.Second) | |
select { | |
case <-ctx.Done(): | |
return fmt.Errorf("you canceled my job!") | |
case <-timeout: | |
return nil | |
} | |
return nil | |
} | |
func main() { | |
ctx, cancel := context.WithCancel(context.Background()) | |
done := make(chan bool) | |
go func() { | |
defer close(done) | |
if err := LongRunning(ctx); err != nil { | |
log.Fatalf("error running LongRunning: %v", err) | |
} | |
}() | |
wait := make(chan os.Signal, 1) | |
signal.Notify(wait, syscall.SIGINT, syscall.SIGTERM) | |
<-wait | |
cancel() // gracefully stop my long running function | |
<-done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment