From a2d06eb1570a5f1e96e9db1f19502e3f988e8f62 Mon Sep 17 00:00:00 2001 From: John Roesler Date: Fri, 29 Sep 2023 14:27:59 -0500 Subject: [PATCH] add GetName() to Job to expose job name (#583) * add GetName() to Job to expose job name * sort examples --- example_test.go | 13 +++++++++++++ job.go | 9 +++++++++ job_test.go | 13 +++++++++++++ 3 files changed, 35 insertions(+) diff --git a/example_test.go b/example_test.go index 2ce1683b..246e20a2 100644 --- a/example_test.go +++ b/example_test.go @@ -34,6 +34,14 @@ func ExampleJob_FinishedRunCount() { s.StartAsync() } +func ExampleJob_GetName() { + s := gocron.NewScheduler(time.UTC) + j, _ := s.Every(1).Second().Name("job_name").Do(task) + fmt.Println(j.GetName()) + // Output: + // job_name +} + func ExampleJob_IsRunning() { s := gocron.NewScheduler(time.UTC) j, _ := s.Every(10).Seconds().Do(func() { time.Sleep(2 * time.Second) }) @@ -71,6 +79,11 @@ func ExampleJob_LimitRunsTo() { s.StartAsync() } +func ExampleJob_Name() { + s := gocron.NewScheduler(time.UTC) + s.Every(1).Second().Name("job_name").Do(task) +} + func ExampleJob_NextRun() { s := gocron.NewScheduler(time.UTC) job, _ := s.Every(1).Second().Do(task) diff --git a/job.go b/job.go index 57fb81f7..c877ba13 100644 --- a/job.go +++ b/job.go @@ -177,6 +177,15 @@ func (j *Job) Name(name string) { j.jobName = name } +// GetName returns the name of the current job. +// The name is either the name set using Job.Name() / Scheduler.Name() or +// the name of the funcion as Go sees it, for example `main.func1` +func (j *Job) GetName() string { + j.mu.Lock() + defer j.mu.Unlock() + return j.jobFunction.getName() +} + func (j *Job) setRandomInterval(a, b int) { j.random.rand = rand.New(rand.NewSource(time.Now().UnixNano())) // nolint diff --git a/job_test.go b/job_test.go index 333e19e8..33b12269 100644 --- a/job_test.go +++ b/job_test.go @@ -232,6 +232,19 @@ func TestJob_CommonExports(t *testing.T) { assert.Equal(t, lastRun, j.LastRun()) } +func TestJob_GetName(t *testing.T) { + s := NewScheduler(time.Local) + j1, _ := s.Every(1).Second().Name("one").Do(func() {}) + assert.Equal(t, "one", j1.GetName()) + + j2, _ := s.Every(1).Second().Do(func() {}) + j2.Name("two") + assert.Equal(t, "two", j2.GetName()) + + j3, _ := s.Every(1).Second().Do(func() {}) + assert.Contains(t, j3.GetName(), "func3") +} + func TestJob_SetEventListeners(t *testing.T) { t.Run("run event listeners callbacks for a job", func(t *testing.T) { var (