Skip to content

Commit

Permalink
add GetName() to Job to expose job name (#583)
Browse files Browse the repository at this point in the history
* add GetName() to Job to expose job name

* sort examples
  • Loading branch information
JohnRoesler authored Sep 29, 2023
1 parent e07c266 commit a2d06eb
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) })
Expand Down Expand Up @@ -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)
Expand Down
9 changes: 9 additions & 0 deletions job.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
13 changes: 13 additions & 0 deletions job_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down

0 comments on commit a2d06eb

Please sign in to comment.