forked from michaloo/go-cron
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathgo-cron.go
124 lines (102 loc) · 2.34 KB
/
go-cron.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package gocron
import (
"github.com/robfig/cron"
"io"
"log"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
type LastRun struct {
Exit_status int
Stdout string
Stderr string
ExitTime string
Pid int
StartingTime string
}
type CurrentState struct {
Running map[string]*LastRun
Last *LastRun
Schedule string
}
var Current_state CurrentState
func copyOutput(out *string, src io.ReadCloser, pid int) {
buf := make([]byte, 1024)
for {
n, err := src.Read(buf)
if n != 0 {
s := string(buf[:n])
*out = *out + s
log.Printf("%d: %v", pid, s)
}
if err != nil {
break
}
}
}
func execute(command string, args []string) {
cmd := exec.Command(command, args...)
run := new(LastRun)
run.StartingTime = time.Now().Format(time.RFC3339)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
log.Fatal(err)
}
if err := cmd.Start(); err != nil {
log.Fatalf("cmd.Start: %v", err)
}
run.Pid = cmd.Process.Pid
Current_state.Running[strconv.Itoa(run.Pid)] = run
go copyOutput(&run.Stdout, stdout, run.Pid)
go copyOutput(&run.Stderr, stderr, run.Pid)
log.Println(run.Pid, "cmd:", command, strings.Join(args, " "))
if err := cmd.Wait(); err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
// The program has exited with an exit code != 0
// so set the error code to tremporary value
run.Exit_status = 127
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
run.Exit_status = status.ExitStatus()
log.Printf("%d Exit Status: %d", run.Pid, run.Exit_status)
}
} else {
log.Fatalf("cmd.Wait: %v", err)
}
}
run.ExitTime = time.Now().Format(time.RFC3339)
delete(Current_state.Running, strconv.Itoa(run.Pid))
//run.Pid = 0
Current_state.Last = run
}
func Create(schedule string, command string, args []string) (cr *cron.Cron, wgr *sync.WaitGroup) {
wg := &sync.WaitGroup{}
c := cron.New()
Current_state = CurrentState{map[string]*LastRun{}, &LastRun{}, schedule}
log.Println("new cron:", schedule)
c.AddFunc(schedule, func() {
wg.Add(1)
execute(command, args)
wg.Done()
})
return c, wg
}
func Start(c *cron.Cron) {
c.Start()
}
func Stop(c *cron.Cron, wg *sync.WaitGroup) {
log.Println("Stopping")
c.Stop()
log.Println("Waiting")
wg.Wait()
log.Println("Exiting")
os.Exit(0)
}