O'Reilly logo

Go Standard Library Cookbook by Radomir Sohlich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Open the console and create the folder chapter04/recipe09.
  2. Navigate to the directory.
  3. Create the ticker.go file with the following content:
        package main        import (          "fmt"          "os"          "os/signal"          "time"       )       func main() {         c := make(chan os.Signal, 1)         signal.Notify(c)         ticker := time.NewTicker(time.Second)         stop := make(chan bool)         go func() {           defer func() { stop <- true }()           for {             select {               case <-ticker.C:                 fmt.Println("Tick")               case <-stop:                 fmt.Println("Goroutine closing")                 return             }           }         }()         // Block until         // the signal is received         <-c         ticker.Stop()         // Stop the goroutine         stop <- true         // Wait until the         <-stop         fmt.Println("Application stopped")       }
  1. Execute the code by running go run ticker.go in the main Terminal.
  2. Wait a few seconds, and then press ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required