This commit is contained in:
John
2019-01-09 13:06:15 +08:00
parent 1c9cb8286f
commit 292fd2f39e
3 changed files with 11 additions and 14 deletions

View File

@ -18,8 +18,8 @@ type Entry struct {
singleton *gtype.Bool // 任务是否单例运行
status *gtype.Int // 任务状态(0: ready; 1: running; -1: closed)
times *gtype.Int64 // 还需运行次数
create int // 注册时的时间轮ticks
interval int // 设置的运行间隔(时间轮刻度数量)
create int64 // 注册时的时间轮ticks
interval int64 // 设置的运行间隔(时间轮刻度数量)
job JobFunc // 注册循环任务方法
}
@ -42,10 +42,10 @@ func (w *Wheel) newEntry(interval time.Duration, job JobFunc, singleton bool, ti
times : gtype.NewInt64(int64(times)),
job : job,
create : ticks,
interval : num,
interval : int64(num),
}
// 计算安装的slot数量(可能多个)
index := ticks%w.number
index := int(ticks%int64(w.number))
for i := 0; i < w.number; i += num {
w.slots[(i + index + num) % w.number].PushBack(entry)
}
@ -88,9 +88,9 @@ func (entry *Entry) Run() {
}
// 检测当前任务是否可运行, 参数为当前时间的纳秒数, 精度更高
func (entry *Entry) runnableCheck(ticks int) bool {
func (entry *Entry) runnableCheck(ticks int64) bool {
diff := ticks - entry.create
if diff > 0 && diff%entry.interval == 0 {
if diff > 0 && diff%int64(entry.interval) == 0 {
// 是否关闭
if entry.status.Val() == STATUS_CLOSED {
return false
@ -102,7 +102,7 @@ func (entry *Entry) runnableCheck(ticks int) bool {
}
}
// 次数限制
if entry.times.Add(-1) <= 0 {
if entry.times.Add(-1) < 0 {
if entry.status.Set(STATUS_CLOSED) == STATUS_CLOSED {
return false
}

View File

@ -21,10 +21,7 @@ func (w *Wheel) startLoop() {
case <- w.ticker.C:
n := w.ticks.Add(1)
l := w.slots[n%w.number]
//if w.interval == 10*time.Millisecond.Nanoseconds() {
// fmt.Println(" loop:", w.ticks.Val(), t, n/1000000)
//}
l := w.slots[int(n%int64(w.number))]
if l.Len() > 0 {
go w.checkEntries(l, n)
}
@ -34,7 +31,7 @@ func (w *Wheel) startLoop() {
}
// 遍历检查可执行循环任务,并异步执行
func (w *Wheel) checkEntries(l *glist.List, ticks int) {
func (w *Wheel) checkEntries(l *glist.List, ticks int64) {
l.RLockFunc(func(list *list.List) {
for e := list.Front(); e != nil; e = e.Next() {
entry := e.Value.(*Entry)

View File

@ -17,7 +17,7 @@ type Wheel struct {
slots []*glist.List // 所有的循环任务项, 按照Slot Number进行分组
number int // Slot Number
closed chan struct{} // 停止事件
ticks *gtype.Int // 当前时间轮已转动的刻度数量
ticks *gtype.Int64 // 当前时间轮已转动的刻度数量
ticker *time.Ticker // 时间轮刻度间隔
interval int64 // 时间间隔(slot时间长度, 纳秒)
}
@ -33,7 +33,7 @@ func New(slot int, interval time.Duration) *Wheel {
slots : make([]*glist.List, slot),
number : slot,
closed : make(chan struct{}, 1),
ticks : gtype.NewInt(),
ticks : gtype.NewInt64(),
ticker : time.NewTicker(interval),
interval : interval.Nanoseconds(),
}