-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathbackoff.go
70 lines (53 loc) · 1.38 KB
/
backoff.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
// Copyright 2014 The sutil Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package stime
import (
"time"
"sync/atomic"
)
type BackOffCtrl struct {
// 退避的最大值
ceil int64
// 退避的起始值
step int64
backtime int64
reset chan bool
}
func NewBackOffCtrl(step time.Duration, ceil time.Duration) *BackOffCtrl {
return &BackOffCtrl {
ceil: ceil.Nanoseconds(),
step: step.Nanoseconds(),
backtime: 0,
reset: make(chan bool),
}
}
func (m *BackOffCtrl) SetCtrl(step time.Duration, ceil time.Duration) {
atomic.StoreInt64(&m.step, step.Nanoseconds())
atomic.StoreInt64(&m.ceil, ceil.Nanoseconds())
m.Reset()
}
// 执行退避,会发生阻塞
func (m *BackOffCtrl) BackOff() {
select {
case <-m.reset:
case <-time.After(time.Duration(atomic.LoadInt64(&m.backtime))):
if atomic.LoadInt64(&m.backtime) <= 0 {
atomic.StoreInt64(&m.backtime, atomic.LoadInt64(&m.step))
} else {
//m.backtime = m.backtime * 2
atomic.StoreInt64(&m.backtime, atomic.LoadInt64(&m.backtime)*2)
}
if atomic.LoadInt64(&m.backtime) >= atomic.LoadInt64(&m.ceil) {
atomic.StoreInt64(&m.backtime, atomic.LoadInt64(&m.ceil))
}
}
}
// 终止退避过程,reset退避状态
func (m *BackOffCtrl) Reset() {
atomic.StoreInt64(&m.backtime, 0)
select {
case m.reset <-true:
default:
}
}