Golang Timer and Ticker

Golang provides two types of timers: time.Timer and time.Ticker. Each have different use Case.

time.Timer is used to create a timer that fires once after the specified duration, while time.Ticker is used to create a timer that fires periodically at the specified interval.

Example 1: Timer

https://goplay.tools/snippet/tSGKq126doi

package main

import (
	"fmt"
	"time"
)

func main() {
	timer := time.NewTimer(2 * time.Second)

	go func() {
		fmt.Println("Inside go routine. Sleeping for 10 seconds")
		time.Sleep(10 * time.Second)
	}()

	<-timer.C
	fmt.Println("Exited after two seconds")
}

Example 2: Ticker

https://goplay.tools/snippet/MiiE4p4fLjb

package main

import (
  "time"
  "fmt"
)

func main() {
  ticker := time.NewTicker(1 * time.Second)

  go func() {
    for t := range ticker.C {
      fmt.Println("Tick at", t)
    }
  }()

  time.Sleep(5 * time.Second)
  ticker.Stop()

  fmt.Println("Ticker stopped")
}