Skip to content

Commit

Permalink
feat: add Context() method and update job retrieval, closes go-co-op#762
Browse files Browse the repository at this point in the history


- Add Context() method to Job interface and implement it in job struct
- Update requestJob function to include a timeout flag
- Modify existing methods to use the new requestJob signature
  • Loading branch information
pcfreak30 committed Oct 21, 2024
1 parent 97e1415 commit febe994
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
15 changes: 11 additions & 4 deletions job.go
Original file line number Diff line number Diff line change
Expand Up @@ -995,6 +995,7 @@ type Job interface {
// Tags returns the job's string tags.
Tags() []string
Lock() Lock
Context() context.Context
}

var _ Job = (*job)(nil)
Expand All @@ -1016,7 +1017,7 @@ func (j job) ID() uuid.UUID {
}

func (j job) LastRun() (time.Time, error) {
ij := requestJob(j.id, j.jobOutRequest)
ij := requestJob(j.id, j.jobOutRequest, true)
if ij == nil || ij.id == uuid.Nil {
return time.Time{}, ErrJobNotFound
}
Expand All @@ -1028,7 +1029,7 @@ func (j job) Name() string {
}

func (j job) NextRun() (time.Time, error) {
ij := requestJob(j.id, j.jobOutRequest)
ij := requestJob(j.id, j.jobOutRequest, true)
if ij == nil || ij.id == uuid.Nil {
return time.Time{}, ErrJobNotFound
}
Expand All @@ -1041,7 +1042,7 @@ func (j job) NextRun() (time.Time, error) {
}

func (j job) NextRuns(count int) ([]time.Time, error) {
ij := requestJob(j.id, j.jobOutRequest)
ij := requestJob(j.id, j.jobOutRequest, true)
if ij == nil || ij.id == uuid.Nil {
return nil, ErrJobNotFound
}
Expand Down Expand Up @@ -1095,7 +1096,13 @@ func (j job) RunNow() error {
}

func (j job) Lock() Lock {
ij := requestJob(j.id, j.jobOutRequest)
ij := requestJob(j.id, j.jobOutRequest, true)

return ij.lastLock
}

func (j job) Context() context.Context {
ij := requestJob(j.id, j.jobOutRequest, false)

return ij.ctx
}
12 changes: 9 additions & 3 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,15 @@ func callJobFuncWithParams(jobFunc any, params ...any) error {
return nil
}

func requestJob(id uuid.UUID, ch chan jobOutRequest) *internalJob {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
func requestJob(id uuid.UUID, ch chan jobOutRequest, timeout bool) *internalJob {
var cancel context.CancelFunc
ctx := context.Background()

if timeout {
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
defer cancel()
}

return requestJobCtx(ctx, id, ch)
}

Expand Down

0 comments on commit febe994

Please sign in to comment.