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") }