Tickers
package main
import (
"fmt"
"time"
)
func main() {
// Creating a ticker 'ticker' that ticks every 500 milliseconds
ticker := time.NewTicker(500 * time.Millisecond)
// Creating a channel 'done' for signaling when to stop the ticker
done := make(chan bool)
// Launching a goroutine to handle ticker events
go func() {
for {
select {
// If a signal is received on the 'done' channel, exit the goroutine
case <-done:
return
// If a tick is received on the 'ticker.C' channel, print the time of the tick
case t := <-ticker.C:
fmt.Println("Tick at", t)
}
}
}()
// Sleeping for 1600 milliseconds to allow several ticks to occur
time.Sleep(1600 * time.Millisecond)
// Stopping the ticker
ticker.Stop()
// Signaling the 'done' channel to stop the goroutine
done <- true
fmt.Println("Ticker stopped")
}Output
Last updated