-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathtickers.go
32 lines (26 loc) · 976 Bytes
/
tickers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main
import (
"fmt"
"time"
)
// Timers are for when you want to do something once in the future -
// tickers are for when you want to do something repeatedly at regular intervals.
// Here’s an example of a ticker that ticks periodically until we stop it.
// Ticker func illuste the use of tickers in go.
func Ticker() {
// Tickers use a similar mechanism to timers:
// a channel that is sent values.
// Here we’ll use the range builtin on the channel to iterate over the values as they arrive every 500ms.
ticker := time.NewTicker(500 * time.Millisecond)
go func() {
for t := range ticker.C {
fmt.Println("Tick at ", t)
}
}()
// Tickers can be stopped like timers.
// Once a ticker is stopped it won’t receive any more values on its channel. We’ll stop ours after 1600ms.
time.Sleep(1600 * time.Millisecond)
ticker.Stop()
fmt.Println("Ticker stopped")
// When we run this program the ticker should tick 3 times before we stop it.
}