123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- package scheduler
- import (
- "sync"
- "time"
- log "github.com/sirupsen/logrus"
- )
- type ScheduledJobConfig struct {
- Task func()
- Period time.Duration
- Name string
- }
- func CreateJob(c ScheduledJobConfig) scheduledJob {
- job := scheduledJob{}
- job.task = c.Task
- job.period = c.Period
- job.name = c.Name
- job.running = false
- job.mux = &sync.Mutex{}
- job.stopChannel = make(chan bool, 1)
- return job
- }
- type scheduledJob struct {
- task func()
- period time.Duration
- running bool
- name string
- stopChannel chan bool
- mux *sync.Mutex
- }
- func (s scheduledJob) run() {
- logContext := log.WithFields(log.Fields{
- "Func": "Run()",
- "package": "scheduler",
- })
- //logContext := log.WithField("Func", "Run")
- for {
- select {
- case <-time.After(s.period):
- case <-s.stopChannel:
- logContext.Debug("Closing Channel")
- close(s.stopChannel)
- s.running = false
- return
- }
- logContext.Debug("Getting lock")
- s.mux.Lock()
- logContext.Debug("Log obtained")
- logContext.Debug("Running Task")
- s.task()
- logContext.Debug("Releasing lock")
- s.mux.Unlock()
- logContext.Debug("Lock Released")
- }
- }
- func (s scheduledJob) Start() {
- logContext := log.WithFields(log.Fields{
- "Func": "Start()",
- "package": "scheduler",
- })
- logContext.Debug("Getting lock")
- s.mux.Lock()
- logContext.Debug("Log obtained")
- s.running = true
- logContext.Info("Starting Job")
- go s.run()
- logContext.Debug("Releasing lock")
- s.mux.Unlock()
- logContext.Debug("Lock Released")
- }
- func (s scheduledJob) Stop() {
- logContext := log.WithFields(log.Fields{
- "Func": "Stop()",
- "package": "scheduler",
- })
- logContext.Debug("Getting lock")
- s.mux.Lock()
- logContext.Debug("Lock obtained")
- s.stopChannel <- false
- logContext.Info("Waiting on job to stop")
- for s.running {
- }
- logContext.Info("Job as stopped")
- logContext.Debug("Releasing lock")
- s.mux.Unlock()
- logContext.Debug("Lock Released")
- }
|