Running the code block periodically
Besides the date and time operations, the time
package also provides support for periodic and delayed code execution. Typically, the application health checks, activity checks, or any periodic job can be implemented this way.
How to do it...
- Open the console and create the folder
chapter04/recipe09
. - Navigate to the directory.
- 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 } ...