diff --git a/errors.go b/errors.go index 53df01b1..7388cb99 100644 --- a/errors.go +++ b/errors.go @@ -38,6 +38,7 @@ var ( ErrWithDistributedElectorNil = fmt.Errorf("gocron: WithDistributedElector: elector must not be nil") ErrWithDistributedLockerNil = fmt.Errorf("gocron: WithDistributedLocker: locker must not be nil") ErrWithDistributedJobLockerNil = fmt.Errorf("gocron: WithDistributedJobLocker: locker must not be nil") + ErrWithIdentifierNil = fmt.Errorf("gocron: WithIdentifier: identifier must not be nil") ErrWithLimitConcurrentJobsZero = fmt.Errorf("gocron: WithLimitConcurrentJobs: limit must be greater than 0") ErrWithLocationNil = fmt.Errorf("gocron: WithLocation: location must not be nil") ErrWithLoggerNil = fmt.Errorf("gocron: WithLogger: logger must not be nil") diff --git a/example_test.go b/example_test.go index 478af1f2..7ac57654 100644 --- a/example_test.go +++ b/example_test.go @@ -694,6 +694,27 @@ func ExampleWithGlobalJobOptions() { // [tag4 tag5 tag6] } +func ExampleWithIdentifier() { + s, _ := NewScheduler() + defer func() { _ = s.Shutdown() }() + + j, _ := s.NewJob( + DurationJob( + time.Second, + ), + NewTask( + func(one string, two int) { + fmt.Printf("%s, %d", one, two) + }, + "one", 2, + ), + WithIdentifier(uuid.MustParse("87b95dfc-3e71-11ef-9454-0242ac120002")), + ) + fmt.Println(j.ID()) + // Output: + // 87b95dfc-3e71-11ef-9454-0242ac120002 +} + func ExampleWithLimitConcurrentJobs() { _, _ = NewScheduler( WithLimitConcurrentJobs( diff --git a/job.go b/job.go index 5b0302c4..0668a5ff 100644 --- a/job.go +++ b/job.go @@ -610,6 +610,20 @@ func WithTags(tags ...string) JobOption { } } +// WithIdentifier sets the identifier for the job. The identifier +// is used to uniquely identify the job and is used for logging +// and metrics. +func WithIdentifier(id uuid.UUID) JobOption { + return func(j *internalJob) error { + if id == uuid.Nil { + return ErrWithIdentifierNil + } + + j.id = id + return nil + } +} + // ----------------------------------------------- // ----------------------------------------------- // ------------- Job Event Listeners ------------- diff --git a/scheduler_test.go b/scheduler_test.go index 58fa6546..ceacc55c 100644 --- a/scheduler_test.go +++ b/scheduler_test.go @@ -774,6 +774,14 @@ func TestScheduler_NewJobErrors(t *testing.T) { []JobOption{WithDistributedJobLocker(nil)}, ErrWithDistributedJobLockerNil, }, + { + "WithIdentifier is nil", + DurationJob( + time.Second, + ), + []JobOption{WithIdentifier(uuid.Nil)}, + ErrWithIdentifierNil, + }, } for _, tt := range tests {