simplify isRunning

This commit is contained in:
Pascal Fischer
2025-01-16 21:54:29 +01:00
parent d45255b1b7
commit d0ab68c599

View File

@@ -46,17 +46,15 @@ func (mock *MockScheduler) IsJobRunning(_ string) bool {
// DefaultScheduler is a generic structure that allows to schedule jobs (functions) to run in the future and cancel them.
type DefaultScheduler struct {
// jobs map holds cancellation channels indexed by the job ID
jobs map[string]chan struct{}
mu *sync.Mutex
isJobRunning map[string]bool
jobs map[string]chan struct{}
mu *sync.Mutex
}
// NewDefaultScheduler creates an instance of a DefaultScheduler
func NewDefaultScheduler() *DefaultScheduler {
return &DefaultScheduler{
jobs: make(map[string]chan struct{}),
isJobRunning: make(map[string]bool),
mu: &sync.Mutex{},
jobs: make(map[string]chan struct{}),
mu: &sync.Mutex{},
}
}
@@ -94,7 +92,6 @@ func (wm *DefaultScheduler) Schedule(ctx context.Context, in time.Duration, ID s
}
ticker := time.NewTicker(in)
wm.isJobRunning[ID] = true
wm.jobs[ID] = cancel
log.WithContext(ctx).Debugf("scheduled a job %s to run in %s. There are %d total jobs scheduled.", ID, in.String(), len(wm.jobs))
@@ -106,7 +103,6 @@ func (wm *DefaultScheduler) Schedule(ctx context.Context, in time.Duration, ID s
case <-cancel:
log.WithContext(ctx).Debugf("scheduled job %s was canceled, stop timer", ID)
ticker.Stop()
wm.isJobRunning[ID] = false
return
default:
log.WithContext(ctx).Debugf("time to do a scheduled job %s", ID)
@@ -118,7 +114,6 @@ func (wm *DefaultScheduler) Schedule(ctx context.Context, in time.Duration, ID s
delete(wm.jobs, ID)
log.WithContext(ctx).Debugf("job %s is not scheduled to run again", ID)
ticker.Stop()
wm.isJobRunning[ID] = false
return
}
// we need this comparison to avoid resetting the ticker with the same duration and missing the current elapsesed time
@@ -136,5 +131,5 @@ func (wm *DefaultScheduler) Schedule(ctx context.Context, in time.Duration, ID s
}
func (wm *DefaultScheduler) IsJobRunning(ID string) bool {
return wm.isJobRunning[ID]
return wm.jobs[ID] != nil
}