job

package
v0.5.5 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package job 提供跨副本互斥的周期任务。

服务一旦跑到两个副本,"每小时清理一次过期数据"这类任务就会同时跑两遍。 多数时候只是浪费,偶尔是数据损坏(对账重复入账、通知重复发送)。 正确做法是给任务加一把集群级的锁,本包用 Postgres 的 advisory lock 实现: 不建表、不留垃圾,持锁连接一断 Postgres 就自动放锁——副本被 kill -9 也不会留下永久锁死的任务。

典型用法是与 appkit.Registry.Worker 组合,生命周期交给框架:

reg.Worker("cleanup", job.Every(pool, job.Task{
	Name:     "ledger.cleanup",
	Interval: time.Hour,
	Run:      svc.CleanupExpired,
}))

抢不到锁的副本跳过本轮,不阻塞、不排队——周期任务迟一轮无所谓, 排队积压才是事故。

Index

Constants

This section is empty.

Variables

View Source
var ErrLocked = errors.New("job: 任务锁被其它副本持有")

ErrLocked 表示锁正被其它副本持有,本轮跳过。

Functions

func Every

func Every(pool *pgxpool.Pool, t Task) func(context.Context) error

Every 返回一个长驻任务函数,交给 appkit.Registry.Worker 运行: 每 Interval 尝试执行一次 t.Run,同一时刻全集群只有一个副本在执行。

首次执行等一个(带抖动的)周期而非立即执行:滚动更新时全部副本几乎同时 起来,立即执行等于所有副本同时抢同一把锁,抢不到的白跑一趟。 ctx 取消时返回 ctx.Err()(框架据此判定正常关停)。 pool 为 nil、Name 为空或 Interval 非正时 panic——都是装配期的编程错误。

func WithLock

func WithLock(ctx context.Context, pool *pgxpool.Pool, name string, fn func(context.Context) error) error

WithLock 在持有 name 的集群锁期间执行 fn。锁被其它副本持有时立即返回 ErrLocked(不阻塞等待)。fn 的错误原样返回。

锁是 Postgres 的 session 级 advisory lock,绑定在一条从池里借出的连接上: fn 执行期间这条连接不可用于其它查询(fn 内部的查询照常从池里另借), 因此 fn 里别做无限期阻塞的事。进程崩溃时连接断开,Postgres 自动放锁。

Types

type Task

type Task struct {
	// Name 是集群内的任务标识,同名任务互斥。跨域可能重名,
	// 建议带域前缀("ledger.cleanup")。必填。
	Name string
	// Interval 是执行周期,必须为正。
	Interval time.Duration
	// Run 是任务体。返回错误只记日志、不中断循环——一次清理失败不该
	// 掀翻整个服务(这点与 outbox relay 不同:relay 挂了事件就停摆了)。
	Run func(context.Context) error
	// Logger 可选,默认 slog.Default()。
	Logger *slog.Logger
}

Task 描述一个周期任务。

Jump to

Keyboard shortcuts

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