From 5b6795aefd84de5ce5fa4c27f2ab63ad4992ade2 Mon Sep 17 00:00:00 2001 From: Yun Date: Fri, 5 Jun 2026 17:56:32 +0800 Subject: [PATCH] =?UTF-8?q?once=E6=B7=BB=E5=8A=A0=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E4=B8=8D=E5=A4=84=E7=90=86=E5=9B=9E=E8=B0=83=E7=9A=84=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- once.go | 11 ++++++++--- option.go | 9 +++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/once.go b/once.go index 195e731..d945d95 100644 --- a/once.go +++ b/once.go @@ -106,7 +106,7 @@ func InitOnce(ctx context.Context, re redis.UniversalClient, keyPrefix string, c return nil, errors.New("redis client is nil") } - if call == nil { + if call == nil && !op.allowNilFunc { op.logger.Errorf(ctx, "worker callback is nil") return nil, errors.New("worker callback is nil") } @@ -144,6 +144,11 @@ func InitOnce(ctx context.Context, re redis.UniversalClient, keyPrefix string, c maxWorkers: op.maxWorkers, } + // 不需要回调 + if call == nil { + return wo, nil + } + // 初始化优先级 if op.priorityType != priorityTypeNone { @@ -497,8 +502,8 @@ func (l *Once) create(ctx context.Context, source createSource, jobType jobType, l.logger.Errorf(l.ctx, "redis.ZScore err:%v", err) return err } - l.logger.Errorf(l.ctx, "task exists taskType:%v taskId:%v attachData:%v runCount:%v", taskType, taskId, attachData, runCount) - return ErrTaskExists + l.logger.Errorf(l.ctx, "task exists taskType:%v taskId:%v attachData:%v runCount:%v", taskType, taskId, attachData, runCount) + return ErrTaskExists } // 删除任务 diff --git a/option.go b/option.go index a245132..1744a7f 100644 --- a/option.go +++ b/option.go @@ -18,6 +18,7 @@ type Options struct { maxRunCount int // 单个任务最大运行次数 0代表不限 maxWorkers int // 最大工作协程数 cronParser *cron.Parser // cron表达式解析器 + allowNilFunc bool // 允许注册nil函数 } type priorityType int8 @@ -43,6 +44,7 @@ func defaultOptions() Options { maxRunCount: 0, maxWorkers: 100, cronParser: &parser, + allowNilFunc: false, } } @@ -80,6 +82,13 @@ func WithLocation(zone *time.Location) Option { } } +// 允许注册nil回调函数 +func WithAllowNilFunc(allow bool) Option { + return func(o *Options) { + o.allowNilFunc = allow + } +} + // 设置任务最长执行时间 func WithTimeout(d time.Duration) Option { return func(o *Options) {