~/Go Tickers Behind the Scenes

Feb 14, 2022


A ticker in Go delivers repeated notifications on a channel after a specified interval. Use it to perform actions at regular intervals without sleeping in a loop.

Quick Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
    "fmt"
    "time"
)

func main() {
    ticker := time.NewTicker(1 * time.Second)
    defer ticker.Stop()
    for i := 0; i < 3; i++ {
        <-ticker.C
        fmt.Println("Tick", i)
    }
}

This code prints “Tick” every second for three seconds.

Stopping a ticker is important to release underlying resources:

1
ticker.Stop()

Unlike time.After, which waits once, time.Ticker repeatedly sends time values. Using tickers is more efficient than manual sleep in periodic jobs.

Common uses include scheduled tasks, polling, and timeouts in concurrent systems. Always remember to stop the ticker to avoid goroutine leaks.

Tags: [golang] [ticker]