-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (67 loc) · 1.83 KB
/
main.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
package main
import (
"context"
_ "embed"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/ismdeep/log"
"github.com/robfig/cron/v3"
"go.uber.org/zap"
)
//go:embed banner.txt
var banner string
var cronCommand string
func runCommandFunc() {
startedAt := time.Now()
log.WithContext(context.Background()).Info("Started")
defer func() {
endedAt := time.Now()
log.WithContext(context.Background()).Info("Ended", zap.String("time_elapsed", endedAt.Sub(startedAt).String()))
log.WithContext(context.Background()).Info("----------------------------------------------------------------------")
fmt.Println()
}()
cmdSlice := strings.Fields(cronCommand)
cmd := exec.Command(cmdSlice[0], cmdSlice[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.WithContext(context.Background()).Error("failed to run task", zap.Error(err))
return
}
log.WithContext(context.Background()).Info("Finished")
}
func main() {
fmt.Println(banner)
cronSpec := os.Getenv("CRON_SPEC")
cronCommand = os.Getenv("CRON_COMMAND")
cronRunAtStart := os.Getenv("CRON_RUN_AT_START")
if cronSpec == "" {
panic("CRON_SPEC is empty")
}
if cronCommand == "" {
panic("CRON_COMMAND is empty")
}
log.WithContext(context.Background()).Info("----------------------------------------------------------------------")
if cronRunAtStart == "true" {
runCommandFunc()
}
c := cron.New(
cron.WithSeconds(),
cron.WithChain(
cron.SkipIfStillRunning(
cron.DefaultLogger)),
)
for _, spec := range strings.Split(cronSpec, "\n") {
spec = strings.TrimSpace(spec)
if spec != "" {
log.WithContext(context.Background()).Info("Cron spec", zap.String("spec", spec))
if _, err := c.AddFunc(spec, runCommandFunc); err != nil {
panic(fmt.Errorf("failed to add cron spec '%s': %v", spec, err))
}
}
}
c.Run()
}