0
0
GoHow-ToBeginner · 3 min read

How to Use Ticker in Go: Simple Guide with Examples

In Go, you use time.NewTicker to create a ticker that sends the current time on a channel at regular intervals. You receive from this channel in a loop to perform repeated actions, and stop the ticker with Stop() when done.
📐

Syntax

The ticker is created using time.NewTicker(duration), where duration is how often you want the ticker to tick. It returns a *time.Ticker which has a channel C that sends the current time at each tick. You use Stop() to stop the ticker and release resources.

go
ticker := time.NewTicker(time.Second * 1)
// ticker.C is the channel that receives time every second
// Use ticker.Stop() to stop the ticker when done
💻

Example

This example shows how to create a ticker that prints a message every second and stops after 5 ticks.

go
package main

import (
	"fmt"
	"time"
)

func main() {
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop() // ensure ticker is stopped when done

	count := 0
	for t := range ticker.C {
		fmt.Println("Tick at", t)
		count++
		if count == 5 {
			break
		}
	}

	fmt.Println("Ticker stopped")
}
Output
Tick at 2024-06-01 12:00:00 +0000 UTC Tick at 2024-06-01 12:00:01 +0000 UTC Tick at 2024-06-01 12:00:02 +0000 UTC Tick at 2024-06-01 12:00:03 +0000 UTC Tick at 2024-06-01 12:00:04 +0000 UTC Ticker stopped
⚠️

Common Pitfalls

One common mistake is not stopping the ticker, which can cause resource leaks. Always call Stop() when the ticker is no longer needed. Another issue is blocking on the ticker channel without a way to exit, which can freeze your program.

Also, do not create a new ticker inside a loop without stopping the old one, as this creates many tickers and wastes resources.

go
package main

import (
	"fmt"
	"time"
)

func main() {
	// Wrong: ticker not stopped
	ticker := time.NewTicker(time.Second)

	for i := 0; i < 3; i++ {
		<-ticker.C
		fmt.Println("Tick", i)
	}

	// Program ends but ticker is still running, wasting resources

	// Right way:
	// ticker.Stop() should be called when done
}
Output
Tick 0 Tick 1 Tick 2
📊

Quick Reference

  • time.NewTicker(d time.Duration): creates a new ticker that ticks every d.
  • ticker.C: channel that receives the time at each tick.
  • ticker.Stop(): stops the ticker to free resources.
  • Use range ticker.C or receive from ticker.C in a loop to handle ticks.

Key Takeaways

Use time.NewTicker to create a ticker that sends time at regular intervals.
Always stop the ticker with Stop() to avoid resource leaks.
Receive from ticker.C channel in a loop to perform repeated actions.
Avoid creating multiple tickers without stopping the old ones.
Use defer ticker.Stop() to ensure ticker is stopped even if function exits early.