Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add GetName() to Job to expose job name #583

Merged
merged 2 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading