From d4fbd2a0903f1631872bfc54c4df2a15c7dd7c22 Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Sun, 25 Jun 2017 19:14:50 +0200 Subject: [PATCH] Implemented job scheduler --- jobs/main.go | 71 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 65 insertions(+), 6 deletions(-) diff --git a/jobs/main.go b/jobs/main.go index 1f1d42b4..d7d635aa 100644 --- a/jobs/main.go +++ b/jobs/main.go @@ -3,16 +3,27 @@ package main import ( "fmt" "os" + "os/exec" "os/signal" "path" "syscall" "time" + "github.com/aerogo/log" "github.com/fatih/color" ) +var colorPool = []*color.Color{ + color.New(color.FgCyan), + color.New(color.FgYellow), + color.New(color.FgGreen), + color.New(color.FgBlue), + color.New(color.FgMagenta), +} + var jobs = map[string]time.Duration{ - "popular-anime": 1 * time.Second, + "popular-anime": 5 * time.Second, + "search-index": 15 * time.Second, } func main() { @@ -24,6 +35,7 @@ func main() { } func startJobs() { + // Get the directory the executable is in exe, err := os.Executable() if err != nil { @@ -32,22 +44,69 @@ func startJobs() { root := path.Dir(exe) - for job, interval := range jobs { - jobInterval := interval - executable := path.Join(root, job, job) + // Log paths + logsPath := path.Join(root, "../", "logs") + jobLogsPath := path.Join(root, "../", "logs", "jobs") + os.Mkdir(jobLogsPath, 0777) - fmt.Printf("Registered job %s for execution every %v\n", color.YellowString(job), interval) + // Scheduler log + mainLog := log.New() + mainLog.AddOutput(os.Stdout) + mainLog.AddOutput(log.File(path.Join(logsPath, "scheduler.log"))) + schedulerLog := mainLog + + // Color index + colorIndex := 0 + + // Start each job + for job, interval := range jobs { + jobName := job + jobInterval := interval + executable := path.Join(root, jobName, jobName) + jobColor := colorPool[colorIndex].SprintFunc() + + jobLog := log.New() + jobLog.AddOutput(log.File(path.Join(jobLogsPath, jobName+".log"))) + + fmt.Printf("Registered job %s for execution every %v\n", jobColor(jobName), interval) go func() { ticker := time.NewTicker(jobInterval) defer ticker.Stop() + var err error + for { - fmt.Println(executable) + schedulerLog.Info("Starting " + jobColor(jobName)) + + cmd := exec.Command(executable) + cmd.Stdout = jobLog + cmd.Stderr = jobLog + + err = cmd.Start() + + if err != nil { + color.Red(err.Error()) + } + + err = cmd.Wait() + + if err != nil { + color.Red(err.Error()) + } + + schedulerLog.Info("Finished " + jobColor(jobName)) + jobLog.Info("--------------------------------------------------------------------------------") + <-ticker.C } }() + + colorIndex = (colorIndex + 1) % len(colorPool) } + + // Finished job registration + println("--------------------------------------------------------------------------------") } func wait() {