timer

package
v1.3.4 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package timer 提供层级时间轮(Hierarchical Timing Wheel),适用于海量延时任务 调度,如帧同步的技能 CD、buff 到期、定时邮件、连接超时、延迟队列等。

设计要点:

  • 多层级级联:低层指针转一圈(归零)时,从高层对应槽位取任务"降级"重新分配到 低层,从而以 O(1) 添加支持任意大延迟,避免单层轮"转很多圈"的浪费。
  • 全程整数运算:用 time.Duration 而非 float64.Seconds(),亚秒级延迟精度无损 (旧实现的浮点转换会让 150ms 之类的延迟全错)。
  • 单调度线程:所有槽位操作在后台 goroutine 内串行执行,无锁;外部 AddTimer / RemoveTimer 经带缓冲 channel 投递请求,绝不阻塞调用方。
  • Stop 幂等无死锁:用 context + sync.Once,不会像旧实现那样向已退出的 goroutine 阻塞发送。
  • job panic 隔离:每个任务回调带 recover,单个 job 崩溃不影响后续 tick。

注意:本包位于 lib/util 工具层,不实现 runtime.Component(避免反向依赖 service 层)。 需要生命周期托管时,由调用方用 runtime.ComponentFunc 包一层,或在新文件中组合。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Job

type Job func(data interface{})

Job 延时任务回调。data 为 AddTimer 时传入的参数。

type Option added in v1.2.5

type Option func(*TimeWheel)

Option 配置 TimeWheel。

func WithAsyncJob added in v1.2.5

func WithAsyncJob(b bool) Option

WithAsyncJob 设置 job 是否在独立 goroutine 中执行。默认 false(同步)。 同步执行保证任务按到期顺序串行处理,适合帧同步等需要确定性时序的场景; 异步执行适合 job 本身较慢且互不相关的场景,但会失去顺序保证并产生无上限 goroutine。

func WithLayers added in v1.2.5

func WithLayers(n int) Option

WithLayers 设置层级数。默认 3。 每加一层,最大延迟扩大 slotNum 倍。默认配置(100ms×60×3层)可表达 6min×60=6h。

func WithSlotNum added in v1.2.5

func WithSlotNum(n int) Option

WithSlotNum 设置每层槽位数。默认 60。所有层共用同一槽位数。 槽位越多,单层能表达的延迟越大,层数越少;权衡内存与层数。

func WithTickInterval added in v1.2.5

func WithTickInterval(d time.Duration) Option

WithTickInterval 设置最低层 tick 周期(即时间轮精度)。默认 100ms。 值越小精度越高但 CPU 开销越大;帧同步场景常见 16ms (~60fps) 或 33ms (~30fps)。

type TimeWheel

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

TimeWheel 层级时间轮。

func NewTimeWheel added in v1.2.5

func NewTimeWheel(job Job, opts ...Option) *TimeWheel

NewTimeWheel 创建层级时间轮。必须在 Start 前配置完毕。

func (*TimeWheel) AddTimer

func (tw *TimeWheel) AddTimer(delay time.Duration, key interface{}, data interface{}) bool

AddTimer 添加一个延时任务。delay 为相对现在的延迟;key 为唯一标识(可用于 RemoveTimer),传 nil 表示匿名任务(不可删除)。delay<=0 立即投递到下一 tick。 非阻塞:channel 缓冲满时返回 false(调用方可据此背压)。

重复 key:新任务会覆盖旧任务的定位索引,旧任务虽仍在槽中但 RemoveTimer 按 key 会定位到新任务;若需严格唯一,调用方自行保证。

func (*TimeWheel) RemoveTimer

func (tw *TimeWheel) RemoveTimer(key interface{})

RemoveTimer 删除任务。key 为 AddTimer 时传入的标识。匿名任务(key=nil)不可删。 非阻塞;key 不存在静默忽略。

func (*TimeWheel) Start

func (tw *TimeWheel) Start(ctx context.Context) context.Context

Start 启动后台调度 goroutine。幂等(多次调用仅首次生效)。返回的 ctx 可用于外部 等待(ctx.Done 在 Stop 后关闭)。

func (*TimeWheel) Stop

func (tw *TimeWheel) Stop()

Stop 停止时间轮。幂等、非阻塞(绝不向已退出 goroutine 阻塞发送)。 停止后未触发的任务不会被执行;在途的 job(asyncJob 模式)不等待。

Jump to

Keyboard shortcuts

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