Tickers can repeat execution of a task every n seconds. This is unlike timers which are used for timeouts. A ticker can repeat a block of code.

Goroutines run concurrently and can have tickers inside them.

Download PDF

Example

time.Tick

You can use the function time.Tick(n). An example call is time.Tick(time.Second * 1). Combined with range that repeats every second.

You can combine it with time.Sleep(n) to make it won’t simply quit while running the goroutine.

package main

import "fmt"
import "time"

func task() {
for range time.Tick(time.Second *1){
fmt.Println("Tick ")
}
}

func main() {
go task()
time.Sleep(time.Second * 5)
}

Tickers

You can create a ticker anywhere in the code with the line time.NewTicker(n).
Then you can use it to tick every interval:

package main

import "fmt"
import "time"

func task() {
ticker := time.NewTicker(time.Second * 1)
for range ticker.C {
fmt.Println("Tick ")
}
}

func main() {
go task()
time.Sleep(time.Second * 5)
}