Created
July 30, 2022 05:23
-
-
Save diego-augusto/bdfeb8f60ae3b4bb513ea1da2cf60d06 to your computer and use it in GitHub Desktop.
Graceful Shutdown in Go
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" | |
"log" | |
"os" | |
"os/signal" | |
"sync" | |
"time" | |
) | |
func main() { | |
// ctx, cancel := context.WithCancel(context.Background()) | |
// defer cancel() | |
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) | |
defer cancel() | |
var wg sync.WaitGroup | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
for { | |
select { | |
case <-ctx.Done(): | |
log.Println("Break the loop 1") | |
return | |
case <-time.After(1 * time.Second): | |
log.Println("loop 1") | |
} | |
} | |
}() | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
for { | |
select { | |
case <-ctx.Done(): | |
log.Println("Break the loop 2") | |
return | |
case <-time.After(2 * time.Second): | |
log.Println("loop 2") | |
} | |
} | |
}() | |
wg.Wait() | |
log.Println("Finishing as a pro!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment