-
Notifications
You must be signed in to change notification settings - Fork 0
xcron
omeyang edited this page Sep 17, 2026
·
1 revision
稳定性:Stable · 覆盖率:94.1% · 源码:
pkg/distributed/xcron
分布式定时任务。基于 robfig/cron,加上锁层(Redis / etcd / Noop)保证多副本同一时刻只有一个执行。
- 定时任务(如每天 00:00 清理过期数据)
- 多副本环境去重(避免每个 pod 都跑一次)
- 任务级钩子(before/after/重试/超时/链路追踪)
import "github.com/omeyang/xkit/pkg/distributed/xcron"
s := xcron.New(
xcron.WithLocker(xcron.NewRedisLocker(redisClient)),
xcron.WithSeconds(),
)
defer s.Stop()
id, err := s.AddFunc("0 */5 * * * *", func(ctx context.Context) error {
return doWork(ctx)
}, xcron.WithName("sync-job"), xcron.WithTimeout(2*time.Minute))
s.Start()| 名称 | 说明 |
|---|---|
Scheduler interface |
AddFunc / AddJob / Remove / Start / Stop / Stats |
Job interface |
Run(ctx) error |
Locker interface |
TryLock(ctx, key, ttl) (LockHandle, error) |
NewRedisLocker / NoopLocker |
锁后端 |
Hook interface |
BeforeJob / AfterJob |
WithSeconds / WithLocker / WithLogger / WithLocation |
调度器选项 |
WithName / WithJobLocker / WithLockTTL / WithTimeout / WithRetry / WithBackoff / WithTracer / WithImmediate / WithHook |
任务选项 |
-
锁键 = 任务名:
WithName必须设,否则无法去重 -
NoopLocker用于单副本环境 -
WithImmediate注册后立即执行一次(不等下次调度时刻) -
任务超时:
WithTimeout通过 ctx cancel 传播