forked from jacexh/ultron
-
Notifications
You must be signed in to change notification settings - Fork 4
/
timer.go
117 lines (96 loc) · 2.44 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
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
package ultron
import (
"encoding/json"
"errors"
"math/rand"
"time"
"github.com/wosai/ultron/v2/pkg/genproto"
)
type (
// Timer 延时器
Timer interface {
Sleep()
}
namedTimer interface {
Timer
Name() string
}
// UniformRandomTimer 平均随机数
UniformRandomTimer struct {
MinWait time.Duration `json:"min_wait,omitempty"`
MaxWait time.Duration `json:"max_wait,omitempty"`
}
// GaussianRandomTimer 高斯分布
GaussianRandomTimer struct {
StdDev float64 `json:"std_dev"` // 标准差
DesiredMean float64 `json:"desired_mean"` // 期望均值
}
// NonstopTimer 不中断
NonstopTimer struct{}
timerConverter struct {
convertDTOFuncs map[string]convertTimerDTOFunc
}
convertTimerDTOFunc func([]byte) (Timer, error)
)
var (
defaultTimerConverter *timerConverter
)
func (urt *UniformRandomTimer) Sleep() {
if urt.MaxWait > 0 {
time.Sleep(urt.MinWait + time.Duration(rand.Int63n(int64(urt.MaxWait-urt.MinWait)+1)))
}
}
func (urt *UniformRandomTimer) Name() string {
return "uniform-random-timer"
}
func (grt *GaussianRandomTimer) Sleep() {
t := time.Duration(rand.NormFloat64()*grt.StdDev + grt.DesiredMean)
if t > 0 {
time.Sleep(t * time.Millisecond)
}
}
func (grt *GaussianRandomTimer) Name() string {
return "gaussion-random-timer"
}
func (ns NonstopTimer) Sleep() {}
func (ns NonstopTimer) Name() string {
return "non-stop-timer"
}
func newTimeConveter() *timerConverter {
return &timerConverter{
convertDTOFuncs: map[string]convertTimerDTOFunc{
"non-stop-timer": func([]byte) (Timer, error) { return NonstopTimer{}, nil },
"gaussion-random-timer": func(data []byte) (Timer, error) {
t := new(GaussianRandomTimer)
err := json.Unmarshal(data, t)
return t, err
},
"uniform-random-timer": func(data []byte) (Timer, error) {
t := new(UniformRandomTimer)
err := json.Unmarshal(data, t)
return t, err
},
},
}
}
func (tc *timerConverter) convertDTO(dto *genproto.TimerDTO) (Timer, error) {
fn, ok := tc.convertDTOFuncs[dto.Type]
if !ok {
return nil, errors.New("cannot find convert func")
}
return fn(dto.Timer)
}
func (tc *timerConverter) convertTimer(t Timer) (*genproto.TimerDTO, error) {
nt, ok := t.(namedTimer)
if !ok {
return nil, errors.New("cannot convert timer")
}
data, err := json.Marshal(nt)
if err != nil {
return nil, err
}
return &genproto.TimerDTO{Type: nt.Name(), Timer: data}, nil
}
func init() {
defaultTimerConverter = newTimeConveter()
}