/
timer.go
60 lines (48 loc) · 965 Bytes
/
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
package jarviscore
import (
"context"
"time"
)
// FuncOnTimer - on timer
// - If it returns false, the timer will end
type FuncOnTimer func(ctx context.Context, timer *Timer) bool
// Timer - timer
type Timer struct {
timer int
ontimer FuncOnTimer
}
// NewTimer - new timer
func NewTimer(timer int, ontimer FuncOnTimer) *Timer {
return &Timer{
timer: timer,
ontimer: ontimer,
}
}
// StartTimer - start timer
func StartTimer(ctx context.Context, timer int, ontimer FuncOnTimer) (*Timer, error) {
if timer <= 0 {
return nil, ErrInvalidTimer
}
if ontimer == nil {
return nil, ErrInvalidTimerFunc
}
t := NewTimer(timer, ontimer)
go t.Start(ctx)
return t, nil
}
// Start - start
func (t *Timer) Start(ctx context.Context) {
ct := time.Second * time.Duration(t.timer)
timer := time.NewTimer(ct)
for {
timer.Reset(ct)
select {
case <-timer.C:
if !t.ontimer(ctx, t) {
break
}
case <-ctx.Done():
break
}
}
}