Go Gopher How to Go

Timers are for when you want to do something once in the future. Here's an example of a timer that fires after a specified duration.

💡 Key Points

  • Timers are used to execute code at a future time.
  • time.NewTimer() creates a new Timer that provides a channel C.
  • The C channel sends the time when the timer fires.
  • Timers can be stopped before they fire by calling the Stop() method.
  • Stop() returns true if the timer was stopped before it fired, false otherwise.

Timer Example

This example shows how to create and stop a timer.

package main

import (
	"fmt"
	"time"
)

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

	<-timer1.C
	fmt.Println("Timer 1 fired")

	timer2 := time.NewTimer(time.Second)
	go func() {
		<-timer2.C
		fmt.Println("Timer 2 fired")
	}()
	stop2 := timer2.Stop()
	if stop2 {
		fmt.Println("Timer 2 stopped")
	}

	time.Sleep(2 * time.Second)
}
Output:
Timer 2 stopped
Timer 1 fired

Timer Operations

OperationSyntaxDescription
Createtimer := time.NewTimer(duration)Creates a new timer.
Wait<-timer.CBlocks until the timer fires.
Stoptimer.Stop()Stops the timer from firing.