/
scheduler.go
92 lines (83 loc) · 2.13 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package procwatch
import (
"encoding/json"
"fmt"
"io/ioutil"
"syscall"
"github.com/golang/glog"
)
//SchedulePath to config
type SchedulePath string
//Schedule Object
type Schedule struct {
Schedule []SchedulerEntity `json:"schedule"`
}
//SchedulerEntity all data required by Procwatch
type SchedulerEntity struct {
Command string `json:"command"`
Restart bool `json:"restart"`
Day string `json:"day"`
Hour string `json:"hour"`
Minute string `json:"minute"`
}
//Parse json from path and return Schedule
func (sc SchedulePath) Parse() (*Schedule, error) {
content, err := ioutil.ReadFile(string(sc))
if err != nil {
return nil, err
}
return parseConfig(content)
}
func parseConfig(content []byte) (*Schedule, error) {
config := &Schedule{}
if err := json.Unmarshal(content, config); err != nil {
return nil, err
}
return config, nil
}
func (w *Watcher) buildJobs() error {
scheduleArr := w.schedule.Schedule
glog.V(1).Infoln("Scheduling Commands: ")
for index := 0; index < len(scheduleArr); index++ {
scheduleEntry := scheduleArr[index]
command := scheduleEntry.Command
restart := scheduleEntry.Restart
day := scheduleEntry.Day
hour := scheduleEntry.Hour
minute := scheduleEntry.Minute
glog.V(1).Infof("Adding Event at %s %s * * %s", minute, hour, day)
if restart {
err := w.cron.AddFunc(fmt.Sprintf("0 %s %s * * %s", minute, hour, day), func() {
if w.useWatcher {
glog.V(2).Infoln("Sending Termination Signal to Process")
err := w.cmd.Process.Signal(syscall.SIGTERM)
if err != nil {
if err.Error() != "not supported by windows" {
glog.Error(err)
}
err := w.cmd.Process.Signal(syscall.SIGKILL)
if err != nil {
glog.Error(err)
}
}
} else {
glog.V(2).Infoln("Sending Restart Command to Channel")
w.cmdChan <- "#restartserver"
}
})
if err != nil {
return err
}
} else {
err := w.cron.AddFunc(fmt.Sprintf("0 %s %s * * %s", minute, hour, day), func() {
glog.V(2).Infoln("Sending Command to Channel: ", command)
w.cmdChan <- command
})
if err != nil {
return err
}
}
}
w.cron.Start()
return nil
}