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
.
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() {
:= time.NewTimer(3 * time.Second)
t1 <- t1.C
.Println("Timer expired")
fmt}
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() {
:= time.NewTimer(time.Second)
t1 go func() {
<-t1.C
.Println("Timer expired")
fmt}()
.Scanln()
fmt:= t1.Stop()
stop if stop {
.Println("Timer stopped")
fmt}
}