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

loop

package
v0.23.2 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package loop 提供周期任务循环原语:ctx 感知 + 单轮 panic 收编 + 忙时丢 tick + 排水。

收编自消费方反复手搓的同一模式(过期清理 / 心跳 / 快照落盘 / 配置轮询等), 把四个易漂移语义一次钉死:

  1. 忙时丢 tick——fn 同步执行、不重叠,执行期间的 tick 直接丢弃
  2. 单轮 panic 不打死循环——按 async.RunSafe 收编(走全局 PanicHandler),循环存活
  3. 停机排水——ctx 取消拦「下一轮」,在飞轮次用独立 ctx 跑完;Wait() 等排水结束
  4. 首跑延迟可被停机打断——FirstDelay 走 select 而非 time.Sleep

用法

ctx, cancel := context.WithCancel(context.Background())
l := loop.Run(ctx, loop.Config{Interval: time.Hour, Name: "expire-sweep"}, func(ctx context.Context) {
    sweep(ctx)
})
// ... 服务运行 ...
cancel()      // 拦下一轮;在飞轮次跑完
l.Wait()      // 排水(超时预算由调用方包一层控制)

语义契约

  • fn 立即(或 FirstDelay 后)首跑,之后每 Interval 一轮
  • fn 内 panic 按 RunSafe 收编,循环存活;Config.Name 非空时汇报带 task 标签
  • 忙时丢 tick(fn 同步执行,不重叠)
  • ctx 取消拦「下一轮」,在飞轮次跑完;Wait() 返回即排水完成
  • Interval <= 0 时按 0 处理(忙轮询),调用方应给合理间隔

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Interval 轮次间隔。<=0 视为 0(只跑首跑轮,避免忙轮询)。
	Interval time.Duration
	// FirstDelay 首跑延迟;0 = 立即首跑。延迟期间 ctx 取消可打断。
	FirstDelay time.Duration
	// Name 可选任务名:panic 汇报带 task 标签(async.RunSafeLabeled),便于按任务聚合。
	Name string
}

Config 周期循环参数。

type Loop

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

Loop 一个正在运行的周期任务循环。

func Run

func Run(ctx context.Context, cfg Config, fn func(ctx context.Context)) *Loop

Run 启动周期循环,立即(或 FirstDelay 后)返回 *Loop,不阻塞调用方。 循环在后台 goroutine 中运行;生命周期由 ctx 控制,排水用 Wait。

func (*Loop) Done

func (l *Loop) Done() <-chan struct{}

Done 返回排水完成信号(Wait 的非阻塞形态)。

func (*Loop) Wait

func (l *Loop) Wait()

Wait 阻塞至循环排水完成(ctx 已取消 且 在飞轮次收尾返回)。 超时预算由调用方配:需要限时排水时用 select 包一层 Done() 或外层 ctx。 可安全重复调用。

Jump to

Keyboard shortcuts

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