-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgoroutine.go
More file actions
277 lines (253 loc) · 6.29 KB
/
goroutine.go
File metadata and controls
277 lines (253 loc) · 6.29 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package com
import (
"context"
"log"
"os"
"os/signal"
"sync"
"sync/atomic"
"time"
)
var (
ErrExitedByContext = context.Canceled
)
func Loop(ctx context.Context, exec func() error, duration time.Duration) error {
if ctx == nil {
ctx = context.Background()
}
check := func() <-chan struct{} {
return ctx.Done()
}
for {
select {
case <-check():
log.Println(CalledAtFileLine(2), ErrExitedByContext)
return ErrExitedByContext
default:
if err := exec(); err != nil {
return err
}
time.Sleep(duration)
}
}
}
// Notify 等待系统信号
// <-Notify()
func Notify(sig ...os.Signal) chan os.Signal {
terminate := make(chan os.Signal, 1)
if len(sig) == 0 {
sig = []os.Signal{os.Interrupt}
}
signal.Notify(terminate, sig...)
return terminate
}
type DelayOncer interface {
Do(parentCtx context.Context, key string, f func() error, delayAndTimeout ...time.Duration) (isNew bool)
DoWithState(parentCtx context.Context, key string, f func(func() bool) error, delayAndTimeout ...time.Duration) (isNew bool)
CloseKey(key string) bool
Close() error
}
func NewDelayOnce(delay time.Duration, timeout time.Duration, debugMode ...bool) DelayOncer {
if timeout <= delay {
panic(`timeout must be greater than delay`)
}
var debug bool
if len(debugMode) > 0 {
debug = debugMode[0]
}
return &delayOnce{
mp: sync.Map{},
delay: delay,
timeout: timeout,
debug: debug,
}
}
// delayOnce 触发之后延迟一定的时间后再执行。如果在延迟处理的时间段内再次触发,则延迟时间基于此处触发时间顺延
// d := NewDelayOnce(time.Second*5, time.Hour)
// ctx := context.TODO()
//
// for i:=0; i<10; i++ {
// d.Do(ctx, `key`,func() error { return nil })
// }
type delayOnce struct {
mp sync.Map
delay time.Duration
timeout time.Duration
debug bool
}
type eventSession struct {
cancel context.CancelFunc
time time.Time
mutex sync.RWMutex
stop chan struct{}
running atomic.Bool
}
func (e *eventSession) Renew(t time.Time) {
e.mutex.Lock()
e.time = t
e.mutex.Unlock()
}
func (e *eventSession) Time() time.Time {
e.mutex.RLock()
t := e.time
e.mutex.RUnlock()
return t
}
func (e *eventSession) Cancel() <-chan struct{} {
e.cancel()
return e.stop
}
func (e *eventSession) Close() {
e.stop <- struct{}{}
close(e.stop)
}
func (d *delayOnce) checkAndStore(parentCtx context.Context, key string, timeout time.Duration) (*eventSession, context.Context) {
v, loaded := d.mp.Load(key)
if loaded {
session := v.(*eventSession)
if session.running.Load() {
return nil, nil
}
if time.Since(session.Time()) < timeout { // 超过 d.timeout 后重新处理
session.Renew(time.Now())
d.mp.Store(key, session)
if d.debug {
log.Println(`[delayOnce] renew time -------------> ` + key)
}
return nil, nil
}
if d.debug {
log.Println(`[delayOnce] cancel -------------> ` + key)
}
select {
case <-session.Cancel():
default:
}
if d.debug {
log.Println(`[delayOnce] canceled -------------> ` + key)
}
if session.running.Load() {
return nil, nil
}
}
ctx, cancel := context.WithCancel(parentCtx)
session := &eventSession{
cancel: cancel,
time: time.Now(),
stop: make(chan struct{}, 1),
}
d.mp.Store(key, session)
return session, ctx
}
func (d *delayOnce) getDelayAndTimeout(delayAndTimeout ...time.Duration) (time.Duration, time.Duration) {
delay := d.delay
timeout := d.timeout
if len(delayAndTimeout) > 0 {
if delayAndTimeout[0] > 0 {
delay = delayAndTimeout[0]
}
if len(delayAndTimeout) > 1 {
if delayAndTimeout[1] > 0 {
timeout = delayAndTimeout[1]
}
}
}
return delay, timeout
}
func (d *delayOnce) Do(parentCtx context.Context, key string, f func() error, delayAndTimeout ...time.Duration) (isNew bool) {
delay, timeout := d.getDelayAndTimeout(delayAndTimeout...)
session, ctx := d.checkAndStore(parentCtx, key, timeout)
if session == nil {
return false
}
go func(key string) {
t := time.NewTicker(time.Second)
defer func() {
t.Stop()
d.mp.Delete(key)
session.Close()
if d.debug {
log.Println(`[delayOnce] close -------------> ` + key)
}
}()
for {
select {
case <-ctx.Done(): // 如果先进入“<-t.C”分支,会等“<-t.C”分支内的代码执行完毕后才有机会执行本分支
return
case <-t.C:
if time.Since(session.Time()) >= delay { // 时间超过d.delay才触发
session.running.Store(true)
err := f()
session.running.Store(false)
session.Cancel()
if err != nil {
log.Println(key+`:`, err)
}
return
}
}
}
}(key)
return true
}
func (d *delayOnce) DoWithState(parentCtx context.Context, key string, f func(func() bool) error, delayAndTimeout ...time.Duration) (isNew bool) {
delay, timeout := d.getDelayAndTimeout(delayAndTimeout...)
session, ctx := d.checkAndStore(parentCtx, key, timeout)
if session == nil {
return false
}
go func(key string) {
var state int32
isAbort := func() bool {
return atomic.LoadInt32(&state) > 0
}
go func() {
<-ctx.Done()
atomic.AddInt32(&state, 1)
}()
t := time.NewTicker(time.Second)
defer func() {
t.Stop()
d.mp.Delete(key)
session.Close()
if d.debug {
log.Println(`[delayOnce] close -------------> ` + key)
}
}()
for {
select {
case <-ctx.Done(): // 如果先进入“<-t.C”分支,会等“<-t.C”分支内的代码执行完毕后才有机会执行本分支
return
case <-t.C:
if time.Since(session.Time()) >= delay { // 时间超过d.delay才触发
session.running.Store(true)
err := f(isAbort)
session.running.Store(false)
session.Cancel()
if err != nil {
log.Println(key+`:`, err)
}
return
}
}
}
}(key)
return true
}
func (d *delayOnce) Close() error {
d.mp.Range(func(key, value interface{}) bool {
session := value.(*eventSession)
session.Cancel()
return true
})
return nil
}
func (d *delayOnce) CloseKey(key string) bool {
v, loaded := d.mp.Load(key)
if loaded {
session := v.(*eventSession)
session.Cancel()
return true
}
return false
}