A timer is a single event in the future. A timer can make the process wait a specified time. When creating the timer, you set the time to wait.

To make a timer expire after 3 seconds, you can use time.NewTimer(3 * time.Second). If you only want to wait, use time.Sleep(3) instead.

If you want to repeat an event, use tickers.

Download PDF

Timers

Example

This program waits for 3 seconds before continuing. The line <- t1.C blocks the timers channel C. It unblocks when the timer has expired.

package main

import "fmt"
import "time"

func main() {
t1 := time.NewTimer(3 * time.Second)
<- t1.C
fmt.Println("Timer expired")
}

Stop timer

Unlike time.Sleep(), a timer can be stopped. In some scenarios you want to be able to cancel a process, like if you download a file or if you are trying to connect.

The program below allows a user to cancel the timer.

package main

import "fmt"
import "time"

func main() {
t1 := time.NewTimer(time.Second)
go func() {
<-t1.C
fmt.Println("Timer expired")
}()

fmt.Scanln()
stop := t1.Stop()
if stop {
fmt.Println("Timer stopped")
}
}