delayqueue

package
v0.3.4 Latest Latest
Warning

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

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

Documentation

Overview

Package delayqueue 提供定点单次触发的延迟任务原语:注册一个未来时刻要执行的 回调,到点由后台 goroutine 触发;支持按 key 取消 / 改期。

与相邻原语的分工:

  • pkg/scheduler 是即时工作池(投递即尽快执行),本包是"定点单次"(delay 后触发);
  • pkg/service/cron 是周期任务(反复触发),本包是一次性(触发即销毁);
  • pkg/ephemeral 是 TTL KV(到点删数据),本包是到点跑回调(可视作 ephemeral 的 "过期即回调"版)。

典型场景(实时游戏 / 社交):开局倒计时、buff/静音到期、房间空闲踢人、订单 15 分钟未支付取消、匹配 60s 超时兜底、限时活动结束结算。

实现:最小堆(按触发时刻排序)+ 单 goroutine 定时器驱动,堆顶最近到期时间用 一个 time.Timer 等待;Schedule/Cancel 通过唤醒信号让驱动 goroutine 重算等待时长。 回调在独立 goroutine 执行(复用 pkg/safe,panic 被恢复),不阻塞驱动循环。

零值不可用,用 New 构造。并发安全。Stop 后驱动 goroutine 退出,未触发的任务丢弃。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option func(*config)

Option 配置 Queue。

func WithOnPanic

func WithOnPanic(fn func(key string, err error)) Option

WithOnPanic 设置回调 panic 时的钩子。err 为 *safe.PanicError(含 panic 值与堆栈)。 不设置时 panic 被 pkg/safe 静默恢复。

type Queue

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

Queue 延迟任务队列。按 key 维护待触发任务,到点单次触发。 零值不可用,用 New 构造。并发安全。

func New

func New(opts ...Option) *Queue

New 创建延迟队列并启动驱动 goroutine。

func (*Queue) Cancel

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

Cancel 取消 key 对应的待触发任务。返回是否确有任务被取消(false=不存在或已触发)。

func (*Queue) Len

func (q *Queue) Len() int

Len 返回当前待触发任务数(有效任务,不含已取消未清理的)。

func (*Queue) Schedule

func (q *Queue) Schedule(key string, delay time.Duration, fn func()) (replaced bool)

Schedule 注册 key 在 delay 后触发 fn。同 key 已存在则改期为新的 delay(覆盖旧任务)。 delay<=0 视为立即触发(下一个驱动循环)。fn 为 nil 时忽略。Stop 后调用返回 false。 返回是否覆盖了已存在的同 key 任务。

func (*Queue) Stop

func (q *Queue) Stop()

Stop 停止驱动 goroutine。幂等。未触发的任务被丢弃。

Jump to

Keyboard shortcuts

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