Skip to content

Commit 4b3f22b

Browse files
committed
adding docs and examples of time.NewTimer
1 parent 26b3395 commit 4b3f22b

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,4 @@ all the examples `Run` functions sequentially in line with the table of contents
2323
* [09 - Slices](slices/main.go)
2424
* [10 - Maps](maps/main.go)
2525
* [11 - Range](ranges/main.go)
26+
* [12 - Timers](timers/main.go)

main.go

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"github.com/symonk/learning-golang/ranges"
1515
"github.com/symonk/learning-golang/slices"
1616
"github.com/symonk/learning-golang/switches"
17+
"github.com/symonk/learning-golang/timers"
1718
"github.com/symonk/learning-golang/values"
1819
"github.com/symonk/learning-golang/variables"
1920
)
@@ -31,6 +32,7 @@ var (
3132
slices.Run,
3233
maps.Run,
3334
ranges.Run,
35+
timers.Run,
3436
}
3537
)
3638

timers/main.go

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package timers
2+
3+
import (
4+
"fmt"
5+
"time"
6+
)
7+
8+
/*
9+
Timers are a great mechanism for achieving:
10+
- Running code at set intervals.
11+
- Running code at some point in the future.
12+
13+
`Tickers` are very similar to `Timers` so take a look at those aswell.
14+
*/
15+
func Run() {
16+
basicTimer()
17+
cancellingATimer()
18+
}
19+
20+
func basicTimer() {
21+
/*
22+
Timers represent a single event in the future. They are underpinned by
23+
an unbuffered channel. Creating a new timer takes a duration after which
24+
it will fire. The channel on a timer is set on the `C` attribute.
25+
*/
26+
timer := time.NewTimer(2 * time.Second)
27+
fmt.Println("Timer started... we are blocking waiting for 2 seconds.")
28+
<-timer.C // wait for the timer channel to be unblocked
29+
fmt.Println("Timer fired after a 2 second delay")
30+
timer.Reset(2 * time.Second)
31+
fmt.Println("Reset the timer to use again!")
32+
<-timer.C
33+
}
34+
35+
func cancellingATimer() {
36+
// Timers can be cancelled before they fire
37+
t := time.NewTimer(60 * time.Second)
38+
// Launch an async goroutine to wait on the timer and fire a task
39+
go func() {
40+
<-t.C
41+
fmt.Println("The timer finished!")
42+
}()
43+
t.Stop()
44+
fmt.Println("The timer was cancelled")
45+
46+
}

0 commit comments

Comments
 (0)