Go Gopher How to 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.

💡 Key Points

  • Tickers are used to perform an action at regular intervals.
  • time.NewTicker() creates a new Ticker that contains a channel C.
  • The C channel sends the time at each tick.
  • Tickers can be stopped by calling the Stop() method.
  • It's important to stop tickers when they are no longer needed to prevent resource leaks.

Ticker Example

This example shows a ticker that ticks every 500 milliseconds. We stop it after 1600 milliseconds.

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")
}
Output:
Tick at ...
Tick at ...
Tick at ...
Ticker stopped

Ticker Operations

OperationSyntaxDescription
Createticker := time.NewTicker(duration)Creates a new ticker.
Receive Tick<-ticker.CBlocks until the next tick.
Stopticker.Stop()Stops the ticker, releasing associated resources.