x
1
// We often want to execute Go code at some point in the
2
// future, or repeatedly at some interval. Go's built-in
3
// _timer_ and _ticker_ features make both of these tasks
4
// easy. We'll look first at timers and then
5
// at [tickers](tickers).
6
7
package main
8
9
import "time"
10
import "fmt"
11
12
func main() {
13
14
// Timers represent a single event in the future. You
15
// tell the timer how long you want to wait, and it
16
// provides a channel that will be notified at that
17
// time. This timer will wait 2 seconds.
18
timer1 := time.NewTimer(time.Second * 2)
19
20
// The `<-timer1.C` blocks on the timer's channel `C`
21
// until it sends a value indicating that the timer
22
// expired.
23
<-timer1.C
24
fmt.Println("Timer 1 expired")
25
26
// If you just wanted to wait, you could have used
27
// `time.Sleep`. One reason a timer may be useful is
28
// that you can cancel the timer before it expires.
29
// Here's an example of that.
30
timer2 := time.NewTimer(time.Second)
31
go func() {
32
<-timer2.C
33
fmt.Println("Timer 2 expired")
34
}()
35
stop2 := timer2.Stop()
36
if stop2 {
37
fmt.Println("Timer 2 stopped")
38
}
39
}
40