-
Notifications
You must be signed in to change notification settings - Fork 9
/
timewheel.go
114 lines (98 loc) · 2.32 KB
/
timewheel.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
// Copyright 2023 sigma
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package timewheel
import (
"context"
"time"
)
// TimeWheel time wheel
type TimeWheel interface {
// TickNext the next tick time
TickNext(ddl time.Duration)
// AddRunner add runner
AddRunner(runner Notify)
// Stop stop the time wheel
Stop()
}
const (
maxTicker = time.Minute * 5
)
// Notify is a function that is called when a timer expires.
type Notify func(context.Context, TimeWheel)
type timeWheel struct {
maxTicker time.Duration
stop chan struct{}
next chan struct{}
stopped chan struct{}
runner []Notify
ctx context.Context
ctxCancel context.CancelFunc
}
// NewTimeWheel new time wheel
func NewTimeWheel(ctx context.Context, maxTickers ...time.Duration) TimeWheel {
t := &timeWheel{
next: make(chan struct{}, 1),
stop: make(chan struct{}, 1),
stopped: make(chan struct{}, 1),
runner: make([]Notify, 0),
}
ctx, ctxCancel := context.WithCancel(ctx)
t.ctx = ctx
t.ctxCancel = ctxCancel
if len(maxTickers) > 0 {
t.maxTicker = maxTickers[0]
} else {
t.maxTicker = maxTicker
}
t.runLoop()
return t
}
// runLoop run loop
func (t *timeWheel) runLoop() {
go func() {
ticker := time.NewTicker(t.maxTicker)
for {
select {
case <-ticker.C:
for _, runner := range t.runner {
go runner(t.ctx, t)
}
case <-t.next:
for _, runner := range t.runner {
go runner(t.ctx, t)
}
case <-t.stop:
t.stopped <- struct{}{}
return
}
}
}()
}
// TickNext tick next
func (t *timeWheel) TickNext(ddl time.Duration) {
go func() {
<-time.After(ddl)
t.next <- struct{}{} // tick next
}()
}
// Stop stop
func (t *timeWheel) Stop() {
t.stop <- struct{}{}
t.ctxCancel()
<-t.stopped
}
// AddRunner add runner
func (t *timeWheel) AddRunner(runner Notify) {
t.runner = append(t.runner, runner)
}