gf/g/os/gtimer/gtimer_loop.go

75 lines
2.2 KiB
Go
Raw Normal View History

2019-01-01 19:43:31 +08:00
// Copyright 2019 gf Author(https://gitee.com/johng/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://gitee.com/johng/gf.
package gtimer
2019-01-01 19:43:31 +08:00
import (
"gitee.com/johng/gf/g/container/glist"
2019-01-11 13:46:40 +08:00
"time"
2019-01-01 19:43:31 +08:00
)
2019-01-09 18:47:11 +08:00
// 开始循环
func (w *wheel) start() {
2019-01-01 19:43:31 +08:00
go func() {
2019-01-11 13:46:40 +08:00
ticker := time.NewTicker(time.Duration(w.intervalMs)*time.Millisecond)
2019-01-01 19:43:31 +08:00
for {
2019-01-09 12:54:37 +08:00
select {
case <- w.closed:
2019-01-11 13:46:40 +08:00
ticker.Stop()
2019-01-09 12:54:37 +08:00
return
2019-01-03 19:11:54 +08:00
2019-01-11 13:46:40 +08:00
case <- ticker.C:
2019-01-09 18:47:11 +08:00
w.proceed()
2019-01-09 12:54:37 +08:00
}
2019-01-01 19:43:31 +08:00
}
}()
}
2019-01-12 20:20:30 +08:00
// 执行时间轮刻度逻辑
2019-01-09 18:47:11 +08:00
func (w *wheel) proceed() {
n := w.ticks.Add(1)
2019-01-11 13:46:40 +08:00
l := w.slots[int(n%w.number)]
2019-01-09 18:47:11 +08:00
if l.Len() > 0 {
2019-01-11 13:46:40 +08:00
go func(l *glist.List, nowTicks int64) {
entry := (*Entry)(nil)
2019-01-12 20:20:30 +08:00
nowMs := time.Now().UnixNano()/1e6
for i := l.Len(); i > 0; i-- {
if v := l.PopFront(); v == nil {
2019-01-12 20:20:30 +08:00
break
} else {
entry = v.(*Entry)
2019-01-12 20:20:30 +08:00
}
if entry.Status() == STATUS_CLOSED {
continue
}
// 是否满足运行条件
if entry.check(nowTicks, nowMs) {
2019-01-09 18:47:11 +08:00
// 异步执行运行
2019-01-12 20:20:30 +08:00
go func(entry *Entry) {
2019-01-09 18:47:11 +08:00
defer func() {
if err := recover(); err != nil {
if err != gPANIC_EXIT {
panic(err)
} else {
entry.Close()
}
}
2019-01-12 20:20:30 +08:00
if entry.Status() == STATUS_RUNNING {
entry.SetStatus(STATUS_READY)
2019-01-09 18:47:11 +08:00
}
}()
2019-01-11 13:46:40 +08:00
entry.job()
2019-01-12 20:20:30 +08:00
}(entry)
}
// 是否继续添运行
if entry.status.Val() != STATUS_CLOSED {
w.reAddEntry(entry, nowTicks, nowMs)
2019-01-09 18:47:11 +08:00
}
2019-01-11 13:46:40 +08:00
}
2019-01-09 18:47:11 +08:00
}(l, n)
}
}