Something went wrong on our end
Select Git revision
-
Volker Schukai authoredVolker Schukai authored
scheduler.go 5.51 KiB
package jobqueue
import (
"fmt"
"github.com/robfig/cron/v3"
"time"
)
type StopChan chan bool
type Scheduler interface {
Schedule(job GenericJob, eventBus *EventBus) error
Cancel(id JobID) error
CancelAll() error
JobExists(id JobID) bool
GetType() string
}
// IntervalScheduler is a scheduler that schedules a job at a fixed interval
type IntervalScheduler struct {
Interval time.Duration
jobs map[JobID]StopChan
}
func (s *IntervalScheduler) Schedule(job GenericJob, eventBus *EventBus) error {
if s.Interval <= 0 {
return fmt.Errorf("invalid interval: %v", s.Interval)
}
if s.jobs == nil {
s.jobs = make(map[JobID]StopChan)
}
id := job.GetID()
if _, ok := s.jobs[id]; ok {
return fmt.Errorf("job %s already scheduled", id)
}
stopChan := make(StopChan)
s.jobs[id] = stopChan
ticker := time.NewTicker(s.Interval)
go func() {
for {
select {
case <-ticker.C:
eventBus.Publish(QueueJob, job)
case <-stopChan:
ticker.Stop()
return
}
}
}()
return nil
}
func (s *IntervalScheduler) GetType() string {
return "Interval"
}
func (s *IntervalScheduler) Cancel(id JobID) error {
if s.jobs == nil {
return nil
}
if stopChan, ok := s.jobs[id]; ok {
stopChan <- true