-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (69 loc) · 1.67 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
82
package main
import (
"log"
"os/exec"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/gorhill/cronexpr"
"github.com/heyyakash/orbis/db"
"github.com/heyyakash/orbis/helpers"
"github.com/heyyakash/orbis/modals"
"github.com/heyyakash/orbis/routes"
)
func Init() {
db.Init()
}
var JobsChannel = make(chan modals.CronJob)
func main() {
Init()
r := gin.Default()
r.GET("/ping", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"message": "pong",
})
})
pool, err := strconv.Atoi(helpers.GetString("POOL"))
if err != nil {
panic("POOL size missing")
}
for i := 1; i <= pool; i++ {
go Worker(JobsChannel, i)
}
go Schedule()
routes.CronRoutes(r)
log.Print("Server Started on port 8080")
r.Run(":8080")
}
func Schedule() {
for {
var jobs []modals.CronJob
result := db.Store.DB.Where("next_run <= ?", time.Now()).Find(&jobs)
if result.Error != nil {
panic(result.Error)
}
for _, job := range jobs {
JobsChannel <- job
}
time.Sleep(1 * time.Minute)
}
}
func Worker(jobChannel <-chan modals.CronJob, label int) {
for job := range jobChannel {
command := strings.Split(job.Command, " ")
cmd := exec.Command(command[0], command[1:]...)
output, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Goroutine %d : Error executing command '%s': %s\n", label, job.Command, err)
} else {
log.Printf("Goroutine %d : Output of command '%s': %s\n", label, job.Command, output)
}
expr, err := cronexpr.Parse(job.Schedule)
if err != nil {
log.Print("Error parsing cron expression for job id = ", job.JobId)
}
nextTime := expr.Next(time.Now())
db.Store.UpdateTimeById("job_id", &job, nextTime, &modals.CronJob{})
}
}