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