Tickers
Examples in
Go
tickers are for when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(500 * time.Millisecond)
done := make(chan bool)
go func() {
for {
select {
case <-done:
return
case t := <-ticker.C:
fmt.Println("Tick at", t)
}
}
}()
time.Sleep(1600 * time.Millisecond)
ticker.Stop()
done <- true
fmt.Println("Ticker stopped")
}
Last Run
:
Tick at 2021-01-29 22:04:49.601892024 +0000 UTC m=+0.500204752
Tick at 2021-01-29 22:04:50.101941423 +0000 UTC m=+1.000254145
Tick at 2021-01-29 22:04:50.601894103 +0000 UTC m=+1.500206871
Ticker stopped