gitlab.com/ignitionrobotics/web/ign-go@v1.0.0-rc4/scheduler/scheduler.go (about) 1 package scheduler 2 3 import ( 4 "gitlab.com/ignitionrobotics/web/ign-go" 5 sch "gitlab.com/ignitionrobotics/web/scheduler" 6 "sync" 7 "time" 8 ) 9 10 // Scheduler represents a generic Scheduler 11 type Scheduler struct { 12 *sch.Scheduler 13 } 14 15 // TaskScheduler defines the basic operations that every Scheduler should fulfill 16 type TaskScheduler interface { 17 DoIn(task func(), seconds int) string 18 DoEvery(task func(), seconds int) string 19 DoAt(task func(), date time.Time) string 20 } 21 22 var once sync.Once 23 var scheduler *Scheduler 24 25 // initializeScheduler instantiate the singleton 26 func initializeScheduler() *ign.ErrMsg { 27 s, err := sch.NewScheduler(1000) 28 if err != nil { 29 return ign.NewErrorMessage(ign.ErrorScheduler) 30 } 31 scheduler = &Scheduler{ 32 Scheduler: s, 33 } 34 return nil 35 } 36 37 // GetInstance returns the scheduler singleton. 38 func GetInstance() *Scheduler { 39 once.Do(func() { 40 initializeScheduler() 41 }) 42 return scheduler 43 } 44 45 // DoIn runs a specific task after a number of seconds. 46 func (s *Scheduler) DoIn(task func(), seconds int) string { 47 return scheduler.Delay().Second(seconds).Do(task) 48 } 49 50 // DoEvery repeatedly runs a task after a number of seconds. 51 func (s *Scheduler) DoEvery(task func(), seconds int) string { 52 return scheduler.Every().Second(seconds).Do(task) 53 } 54 55 // DoAt runs a task on a specific date. 56 // If the date is in the past, DoAt will run instantly. 57 func (s *Scheduler) DoAt(task func(), date time.Time) string { 58 now := time.Now() 59 diff := date.Sub(now) 60 61 seconds := int(diff.Seconds()) 62 63 if seconds < 0 { 64 seconds = 0 65 } 66 67 return s.DoIn(task, seconds) 68 }