1 Star 0 Fork 0

lichun-123 / leaf

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
timer.go 1.43 KB
一键复制 编辑 原始数据 按行查看 历史
lichun-123 提交于 2023-10-05 17:04 . proto update
package timer
import (
"gitee.com/lichun-123/leaf/conf"
"gitee.com/lichun-123/leaf/log"
"runtime"
"time"
)
// one dispatcher per goroutine (goroutine not safe)
type Dispatcher struct {
ChanTimer chan *Timer
}
func NewDispatcher(l int) *Dispatcher {
disp := new(Dispatcher)
disp.ChanTimer = make(chan *Timer, l)
return disp
}
// Timer
type Timer struct {
t *time.Timer
cb func()
}
func (t *Timer) Stop() {
t.t.Stop()
t.cb = nil
}
func (t *Timer) Cb() {
defer func() {
t.cb = nil
if r := recover(); r != nil {
if conf.LenStackBuf > 0 {
buf := make([]byte, conf.LenStackBuf)
l := runtime.Stack(buf, false)
log.Error("%v: %s", r, buf[:l])
} else {
log.Error("%v", r)
}
}
}()
if t.cb != nil {
t.cb()
}
}
func (disp *Dispatcher) AfterFunc(d time.Duration, cb func()) *Timer {
t := new(Timer)
t.cb = cb
t.t = time.AfterFunc(d, func() {
disp.ChanTimer <- t
})
return t
}
// Cron
type Cron struct {
t *Timer
}
func (c *Cron) Stop() {
if c.t != nil {
c.t.Stop()
}
}
func (disp *Dispatcher) CronFunc(cronExpr *CronExpr, _cb func()) *Cron {
c := new(Cron)
now := time.Now()
nextTime := cronExpr.Next(now)
if nextTime.IsZero() {
return c
}
// callback
var cb func()
cb = func() {
defer _cb()
now := time.Now()
nextTime := cronExpr.Next(now)
if nextTime.IsZero() {
return
}
c.t = disp.AfterFunc(nextTime.Sub(now), cb)
}
c.t = disp.AfterFunc(nextTime.Sub(now), cb)
return c
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/lichun-123/leaf.git
git@gitee.com:lichun-123/leaf.git
lichun-123
leaf
leaf
v0.0.6

搜索帮助

344bd9b3 5694891 D2dac590 5694891