File tree 3 files changed +49
-0
lines changed
3 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -23,3 +23,4 @@ all the examples `Run` functions sequentially in line with the table of contents
23
23
* [ 09 - Slices] ( slices/main.go )
24
24
* [ 10 - Maps] ( maps/main.go )
25
25
* [ 11 - Range] ( ranges/main.go )
26
+ * [ 12 - Timers] ( timers/main.go )
Original file line number Diff line number Diff line change @@ -14,6 +14,7 @@ import (
14
14
"github.com/symonk/learning-golang/ranges"
15
15
"github.com/symonk/learning-golang/slices"
16
16
"github.com/symonk/learning-golang/switches"
17
+ "github.com/symonk/learning-golang/timers"
17
18
"github.com/symonk/learning-golang/values"
18
19
"github.com/symonk/learning-golang/variables"
19
20
)
31
32
slices .Run ,
32
33
maps .Run ,
33
34
ranges .Run ,
35
+ timers .Run ,
34
36
}
35
37
)
36
38
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments