Skip to content

Instantly share code, notes, and snippets.

@sgmac
Created April 10, 2018 14:47
Show Gist options
  • Save sgmac/fd664955545d23ea832f622b081d9a01 to your computer and use it in GitHub Desktop.
Save sgmac/fd664955545d23ea832f622b081d9a01 to your computer and use it in GitHub Desktop.
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