timerqueue

package
v0.9.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 21, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

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

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

func WithChannelSize(n int) Option

WithChannelSize 设置命令 channel 容量(添加/取消任务的缓冲)。默认 1024。

func WithName

func WithName(name string) Option

WithName 设置队列名(日志/String 标识)。

func WithPanicHandler

func WithPanicHandler(fn func(taskID string, r any, stack []byte)) Option

WithPanicHandler 设置回调 panic 时的恢复处理。默认仅 slog.Error。

func WithResolution

func WithResolution(d time.Duration) Option

WithResolution 设置轮询精度(堆顶检查间隔)。默认 100ms。 越小越精确但 CPU 开销越高;SLG 场景 100~200ms 足够。

func WithSyncCallback

func WithSyncCallback(sync bool) Option

WithSyncCallback 设置回调同步执行(在主循环 goroutine 内)。 仅当回调极轻量(如写 channel、设标志)时使用;否则会阻塞后续到期任务的检查。 默认 false:回调在独立 goroutine 中异步执行。

type Queue

type Queue struct {
	// contains filtered or unexported fields
}

Queue 是最小堆延时任务队列。零值不可用,用 New 构造。

func New

func New(opts ...Option) *Queue

New 创建延时任务队列(未启动)。用 Start 启动。

func (*Queue) Add

func (q *Queue) Add(id string, delay time.Duration, fn func()) bool

Add 添加一个延时任务。delay 为相对当前的延迟时长;fn 为到期回调。 返回任务 ID(可用于 Cancel)。id 为空时不可取消(但仍会到期执行)。 队列未启动或已停止时返回 false。

func (*Queue) AddAt

func (q *Queue) AddAt(id string, executeAt time.Time, fn func()) bool

AddAt 添加一个在绝对时刻 executeAt 到期的任务。

func (*Queue) Cancel

func (q *Queue) Cancel(id string) bool

Cancel 取消指定 ID 的任务。尚未到期的任务被移除;已到期/已执行的无效果。 返回 false 表示命令 channel 已满或队列已停止。

func (*Queue) Pending

func (q *Queue) Pending() int64

Pending 返回队列中待执行的任务数(近似)。

func (*Queue) Ready

func (q *Queue) Ready() <-chan struct{}

Ready 在主循环启动后关闭——满足 beauty.ReadyNotifier。

func (*Queue) Start

func (q *Queue) Start(ctx context.Context) error

Start 启动主循环,直到 ctx 取消——满足 beauty.Service。

func (*Queue) String

func (q *Queue) String() string

String 满足 beauty.Service。

type Task

type Task struct {
	// ID 任务唯一标识,用于取消。
	ID string

	// ExecuteAt 绝对到期时刻。
	ExecuteAt time.Time

	// Fn 到期后执行的回调。默认在独立 goroutine 中异步调用(WithSyncCallback
	// 可改为同步,但会阻塞时间轴——仅当回调极轻量时使用)。
	Fn func()
	// contains filtered or unexported fields
}

Task 是一个延时任务。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL