/
timer.go
68 lines (57 loc) · 1.49 KB
/
timer.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
package utils
import (
"time"
)
// TimeoutState indicates the state of Timeout class
type TimeoutState int
// Enum for different TimeoutState
const (
Active TimeoutState = iota
Inactive
Expired
)
// Timeout is the implementation of timeout
type Timeout struct {
state TimeoutState
d time.Duration
start time.Time
}
// NewTimeout creates a new timeout class
func NewTimeout(d time.Duration) *Timeout {
timeout := Timeout{state: Inactive, d: d, start: time.Now()}
return &timeout
}
// Start starts the timeout clock
func (timeout *Timeout) Start() {
timeout.state = Active
timeout.start = time.Now()
}
// Stop stops the timeout clock
func (timeout *Timeout) Stop() {
timeout.state = Inactive
timeout.start = time.Now()
}
// CheckExpire checks whether the timeout is reached/expired
func (timeout *Timeout) CheckExpire() bool {
if timeout.state == Active && time.Since(timeout.start) > timeout.d {
timeout.state = Expired
}
if timeout.state == Expired {
return true
}
return false
}
// Duration returns the duration period of timeout
func (timeout *Timeout) Duration() time.Duration {
return timeout.d
}
// SetDuration set new duration for the timer
func (timeout *Timeout) SetDuration(nd time.Duration) {
timeout.d = nd
}
// IsActive checks whether timeout clock is active;
// A timeout is active means it's not stopped caused by stop
// and also not expired with time elapses longer than duration from start
func (timeout *Timeout) IsActive() bool {
return timeout.state == Active
}