Created
April 10, 2018 14:47
-
-
Save sgmac/fd664955545d23ea832f622b081d9a01 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"os" | |
"os/signal" | |
"sync" | |
"syscall" | |
"time" | |
) | |
func main() { | |
var wg sync.WaitGroup | |
ticker := time.NewTicker(2 * time.Second) | |
ctx, cancel := context.WithCancel(context.Background()) | |
signalCh := make(chan os.Signal, 1) | |
signal.Notify(signalCh, syscall.SIGSTOP, syscall.SIGQUIT, syscall.SIGTERM, os.Interrupt) | |
go func() { | |
s := <-signalCh | |
fmt.Println("Got signal ", s) | |
fmt.Println("Clean up connections...") | |
wg.Done() | |
cancel() | |
}() | |
wg.Add(2) | |
go doSomething(ctx, ticker, &wg) | |
fmt.Println("Goroutines started..") | |
wg.Wait() | |
fmt.Println("Done with waiting") | |
} | |
func doSomething(ctx context.Context, ticker *time.Ticker, wg *sync.WaitGroup) { | |
for { | |
select { | |
case <-ctx.Done(): | |
fmt.Println("Context is done") | |
wg.Done() | |
return | |
case <-ticker.C: | |
fmt.Println("Ticker running") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment