Skip to content
Snippets Groups Projects
Select Git revision
  • cd6f8a804c96b40483ae799804683cfb54e38518
  • master default protected
  • 1.31
  • 4.28.0
  • 4.27.0
  • 4.26.0
  • 4.25.5
  • 4.25.4
  • 4.25.3
  • 4.25.2
  • 4.25.1
  • 4.25.0
  • 4.24.3
  • 4.24.2
  • 4.24.1
  • 4.24.0
  • 4.23.6
  • 4.23.5
  • 4.23.4
  • 4.23.3
  • 4.23.2
  • 4.23.1
  • 4.23.0
23 results

devenv.nix

Blame
  • 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