-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtimer.go
129 lines (106 loc) · 2.28 KB
/
mtimer.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Hello World")
t := NewTimer()
t.SetTime(5, 26, 30)
t.Start()
t.DisplayTime(true)
time.Sleep(3000 * time.Millisecond)
t.Reset()
// time.Sleep(3000 * time.Millisecond)
// t.Start()
// time.Sleep(3000 * time.Millisecond)
// t.Stop()
for {}
}
// timer data set
type Timer struct {
seconds, minutes, hours int
flagChan chan bool
displayTime bool // whether display time on console
periodAction []func()
momentAction []func()
}
// create a new timer
func NewTimer() Timer {
t := Timer{
seconds : 0,
minutes : 0,
hours : 0,
flagChan: make(chan bool),
displayTime: false}
return t
}
// a clocktick
func clockTick(t *Timer) {
for {
// display time according to setting
if t.displayTime {
fmt.Println(t.GetTime())
}
// time of 1 second
time.Sleep(1000 * time.Millisecond)
// calculate new time
t.seconds++
if t.seconds == 60 {
t.minutes++
t.seconds = 0
}
if t.minutes == 60 {
t.hours++
}
// declaring flag
var isStop bool
// receive flag status from chan
select {
case isStop = <- t.flagChan:
default:
}
// stop timer according to flag status
if isStop {
break
}
}
}
// start the timer
func (t *Timer) Start() {
go clockTick(t)
}
// stop the timer
func (t *Timer) Stop() {
t.flagChan <- true
}
// reset the timer to 00:00:00
func (t *Timer) Reset() {
t.seconds = 0
t.minutes = 0
t.hours = 0
}
// set the timer of the timer
func (t *Timer) SetTime(hour, minute, second int) {
t.hours = hour
t.minutes = minute
t.seconds = second
}
// configure the timer to display the timer on console or not
func (t *Timer) DisplayTime(isDisplay bool) {
t.displayTime = isDisplay
}
// get the current time string
func (t *Timer) GetTime() string {
return fmt.Sprintf("%.2d:%.2d:%.2d", t.hours, t.minutes, t.seconds)
}
// print time on console
func (t *Timer) PrintTime() {
fmt.Printf(t.GetTime())
}
// set a callback function as moment action that will be executed in a defined time
func (t *Timer) SetMomentAction(hour, minute, second int, fn func()) {
}
// set a callback function as a period action that will be executed periodically after a period
func (t *Timer) SetPeriodAction(period int, fn func()) {
}