Help us shape the future of Go! Take the 2026 Go Developer Survey

timewheel

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package timewheel 提供单级时间轮:海量短延迟定时任务的高效调度结构, 加延迟/移动/删除均为 O(1),触发扫描均摊 O(1)(每 tick 只扫一个槽位)。

设计参考 go-zero collection.TimingWheel(单级时间轮 + 圈数 circle 处理 超出一轮的延迟),差异点:

  • 任务类型收敛为 func()(类型安全,触发经 async.RunSafe 隔离 panic);
  • Ticker 可注入(WithWheelTicker),时序测试完全确定;
  • 生命周期遵循本仓硬规则:Close(ctx) error 幂等关闭。

与 timertask 仓的分工:本包是纯进程内延迟调度(无持久化、无分布式分片); 需要持久化/死信/分片认领请用 github.com/oekit/timertask。

用法:

tw := timewheel.NewTimingWheel(100*time.Millisecond, 64)
defer tw.Close(context.Background())
tw.SetTimer("session:42", func() { expireSession(42) }, 30*time.Second)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Ticker

type Ticker interface {
	C() <-chan time.Time
	Stop()
}

Ticker 周期信号源抽象(与 batch.Ticker 同形;各自独立定义避免子包耦合), 注入手动实现即可确定性地驱动时序测试。

type TickerFactory

type TickerFactory func(d time.Duration) Ticker

TickerFactory 按给定间隔构造 Ticker。

type TimingWheel

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

TimingWheel 单级时间轮:所有操作经事件 channel 串行到唯一后台循环 (无锁),每 tick 推进一格并触发到期任务。

已到期未触发的任务在 Close 后丢弃(不保证触发);需要持久化/重试语义 请用 github.com/oekit/timertask。

func NewTimingWheel

func NewTimingWheel(interval time.Duration, numSlots int, opts ...WheelOption) *TimingWheel

NewTimingWheel 创建并启动时间轮。interval 为每格时长(必须 >0), numSlots 为格数(必须 >0);二者决定可表达的单轮范围 interval×numSlots, 更长延迟由圈数表达。参数非法属于编程错误,直接 panic。

func (*TimingWheel) Close

func (tw *TimingWheel) Close(ctx context.Context) error

Close 幂等关闭:停止事件循环,未触发的任务被丢弃。等待退出最多到 ctx 结束,超时返回 ctx.Err()。

func (*TimingWheel) HasTimer

func (tw *TimingWheel) HasTimer(key any) bool

HasTimer 返回 key 是否有未触发的定时任务。

func (*TimingWheel) MoveTimer

func (tw *TimingWheel) MoveTimer(key any, delay time.Duration)

MoveTimer 调整已存在 key 的触发延迟(保留原任务);key 不存在为 no-op。

func (*TimingWheel) RemoveTimer

func (tw *TimingWheel) RemoveTimer(key any)

RemoveTimer 删除已存在的定时任务;key 不存在为 no-op。

func (*TimingWheel) SetTimer

func (tw *TimingWheel) SetTimer(key any, task func(), delay time.Duration)

SetTimer 注册定时任务:delay 后触发 task(key 已存在时替换旧任务)。 delay 不足一格自动取一格;key 必须为可比较类型(编程错误直接 panic)。

type WheelOption

type WheelOption func(*wheelOptions)

WheelOption 时间轮的可选参数。

func WithWheelTicker

func WithWheelTicker(f TickerFactory) WheelOption

WithWheelTicker 注入周期信号源工厂。nil 工厂被忽略。

Jump to

Keyboard shortcuts

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