Documentation
¶
Overview ¶
Package timerqueue 提供基于最小堆的延时任务队列,由单协程驱动,适用于海量 倒计时场景(如 SLG 建筑升级、科技研究、造兵、Buff 过期等)。
与 pkg/service/cron 的区别:cron 按 cron 表达式周期触发(少量定时), timerqueue 按绝对到期时间调度(万级一次性倒计时),内部用最小堆而非每任务 一个 goroutine/timer,内存与 runtime 开销极低。
与 pkg/scheduler 的区别:scheduler 是事件驱动的工作池(Submit 即消费), timerqueue 则在指定时刻到期后才执行回调——"延时"是核心语义。
设计:单 goroutine 轮询最小堆堆顶,到期即弹出执行;添加/取消任务通过 channel 串行提交,无锁竞争。回调默认在独立 goroutine 中异步执行,不阻塞 时间轴。精度由 WithResolution 控制(默认 100ms)。
实现 beauty.Service(Start/String)+ ReadyNotifier,可直接 beauty.WithService(queue) 挂进框架,随 app 优雅停机。
零值不可用,用 New 构造。
Index ¶
- type Option
- type Queue
- func (q *Queue) Add(id string, delay time.Duration, fn func()) bool
- func (q *Queue) AddAt(id string, executeAt time.Time, fn func()) bool
- func (q *Queue) Cancel(id string) bool
- func (q *Queue) Pending() int64
- func (q *Queue) Ready() <-chan struct{}
- func (q *Queue) Start(ctx context.Context) error
- func (q *Queue) String() string
- type Task
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Option ¶
type Option func(*Queue)
Option 配置 Queue。
func WithChannelSize ¶
WithChannelSize 设置命令 channel 容量(添加/取消任务的缓冲)。默认 1024。
func WithPanicHandler ¶
WithPanicHandler 设置回调 panic 时的恢复处理。默认仅 slog.Error。
func WithResolution ¶
WithResolution 设置轮询精度(堆顶检查间隔)。默认 100ms。 越小越精确但 CPU 开销越高;SLG 场景 100~200ms 足够。
func WithSyncCallback ¶
WithSyncCallback 设置回调同步执行(在主循环 goroutine 内)。 仅当回调极轻量(如写 channel、设标志)时使用;否则会阻塞后续到期任务的检查。 默认 false:回调在独立 goroutine 中异步执行。
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue 是最小堆延时任务队列。零值不可用,用 New 构造。
func (*Queue) Add ¶
Add 添加一个延时任务。delay 为相对当前的延迟时长;fn 为到期回调。 返回任务 ID(可用于 Cancel)。id 为空时不可取消(但仍会到期执行)。 队列未启动或已停止时返回 false。
func (*Queue) Ready ¶
func (q *Queue) Ready() <-chan struct{}
Ready 在主循环启动后关闭——满足 beauty.ReadyNotifier。