Skip to content

Commit a780ddf

Browse files
committed
adding documentation around time.Ticker
1 parent 43ca526 commit a780ddf

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

tickers/main.go

+32
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,37 @@
11
package tickers
22

3+
import (
4+
"fmt"
5+
"time"
6+
)
7+
8+
/*
9+
`Timers` are useful if you want to do something once in the future.
10+
Tickers are for when you want to do something repeatidly at set
11+
intervals, thing of `cron` on linux for example. A ticker will
12+
periodically tick until told to stop.
13+
*/
314
func Run() {
15+
basicTicker()
16+
}
17+
18+
func basicTicker() {
19+
ticker := time.NewTicker(1 * time.Second)
20+
done := make(chan bool) // Make a new channel to track if we are 'done'.
421

22+
go func() {
23+
for {
24+
select {
25+
case <-done:
26+
// We have finished, the ticker has been stopped.
27+
return
28+
case <-ticker.C:
29+
fmt.Println("Ticked again")
30+
}
31+
}
32+
}()
33+
time.Sleep(6 * time.Second)
34+
ticker.Stop()
35+
done <- true
36+
fmt.Printf("Stopped the ticker, ticked %d times", len(done))
537
}

0 commit comments

Comments
 (0)