Skip to content

Instantly share code, notes, and snippets.

@akm
Created June 5, 2024 05:43
Show Gist options
  • Save akm/d823c9e0989284e03bfeb909499b8da8 to your computer and use it in GitHub Desktop.
Save akm/d823c9e0989284e03bfeb909499b8da8 to your computer and use it in GitHub Desktop.
Graceful Shutdown example
package main
import (
"context"
"fmt"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
defer func() {
signal.Stop(sigCh)
cancel()
}()
go func() {
select {
case sig := <-sigCh:
fmt.Printf("[warning] Got signal %s, trying to shutdown gracefully...\n", sig.String())
cancel()
case <-ctx.Done():
fmt.Printf("process is quitting normally\n")
}
}()
if err := run(ctx, os.Args[1:]); err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
}
func run(ctx context.Context, args []string) error {
parseInt := func(s string) int {
v, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return v
}
interval := parseInt(args[0])
count := parseInt(args[1])
fmt.Printf("interval: %d, count: %d\n", interval, count)
fmt.Printf("Run ' kill -TERM %d ' to stop\n", os.Getpid())
for i := 0; i < count; i++ {
select {
case <-ctx.Done():
fmt.Printf("run function is quitting by ctx.Done() \n")
// return fmt.Errorf("run function is stopped")
return ctx.Err()
default:
}
fmt.Printf("run function is running... %d\n", i)
time.Sleep(time.Duration(interval) * time.Second)
}
fmt.Printf("run function is quitting normally\n")
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment