scheduler.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package scheduler
  2. import (
  3. "sync"
  4. "time"
  5. log "github.com/sirupsen/logrus"
  6. )
  7. type ScheduledJobConfig struct {
  8. Task func()
  9. Period time.Duration
  10. Name string
  11. }
  12. func CreateJob(c ScheduledJobConfig) scheduledJob {
  13. job := scheduledJob{}
  14. job.task = c.Task
  15. job.period = c.Period
  16. job.name = c.Name
  17. job.running = false
  18. job.mux = &sync.Mutex{}
  19. job.stopChannel = make(chan bool, 1)
  20. return job
  21. }
  22. type scheduledJob struct {
  23. task func()
  24. period time.Duration
  25. running bool
  26. name string
  27. stopChannel chan bool
  28. mux *sync.Mutex
  29. }
  30. func (s scheduledJob) run() {
  31. logContext := log.WithFields(log.Fields{
  32. "Func": "Run()",
  33. "package": "scheduler",
  34. })
  35. //logContext := log.WithField("Func", "Run")
  36. for {
  37. select {
  38. case <-time.After(s.period):
  39. case <-s.stopChannel:
  40. logContext.Debug("Closing Channel")
  41. close(s.stopChannel)
  42. s.running = false
  43. return
  44. }
  45. logContext.Debug("Getting lock")
  46. s.mux.Lock()
  47. logContext.Debug("Log obtained")
  48. logContext.Debug("Running Task")
  49. s.task()
  50. logContext.Debug("Releasing lock")
  51. s.mux.Unlock()
  52. logContext.Debug("Lock Released")
  53. }
  54. }
  55. func (s scheduledJob) Start() {
  56. logContext := log.WithFields(log.Fields{
  57. "Func": "Start()",
  58. "package": "scheduler",
  59. })
  60. logContext.Debug("Getting lock")
  61. s.mux.Lock()
  62. logContext.Debug("Log obtained")
  63. s.running = true
  64. logContext.Info("Starting Job")
  65. go s.run()
  66. logContext.Debug("Releasing lock")
  67. s.mux.Unlock()
  68. logContext.Debug("Lock Released")
  69. }
  70. func (s scheduledJob) Stop() {
  71. logContext := log.WithFields(log.Fields{
  72. "Func": "Stop()",
  73. "package": "scheduler",
  74. })
  75. logContext.Debug("Getting lock")
  76. s.mux.Lock()
  77. logContext.Debug("Lock obtained")
  78. s.stopChannel <- false
  79. logContext.Info("Waiting on job to stop")
  80. for s.running {
  81. }
  82. logContext.Info("Job as stopped")
  83. logContext.Debug("Releasing lock")
  84. s.mux.Unlock()
  85. logContext.Debug("Lock Released")
  86. }