Skip to content

Instantly share code, notes, and snippets.

@maelvls
Last active September 23, 2019 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maelvls/1df2d49f017ca0e65d1e7fd83f81d28e to your computer and use it in GitHub Desktop.
Save maelvls/1df2d49f017ca0e65d1e7fd83f81d28e to your computer and use it in GitHub Desktop.
Graceful shutdown with Context + channels (https://play.golang.org/p/ZBxNMddpbj2)
// 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