From c08aadda4f45b1e5f3fd58ffa66fe81e45149d29 Mon Sep 17 00:00:00 2001 From: nxshock Date: Tue, 10 May 2022 21:36:34 +0500 Subject: [PATCH] Move run tries to separate func --- job.go | 83 +++++++++++++++++++++++++++++++--------------------------- 1 file changed, 44 insertions(+), 39 deletions(-) diff --git a/job.go b/job.go index 29932fd..410ad2b 100644 --- a/job.go +++ b/job.go @@ -118,45 +118,7 @@ func (j *Job) Run() { defer jobLogFile.Close() for i := 0; i < j.JobConfig.NumberOfRestartAttemts+1; i++ { - log.Info("Started.") - startTime := time.Now() - - globalMutex.Lock() - j.CurrentRunningCount++ - j.Status = Running - j.LastStartTime = startTime.Format(config.TimeFormat) - globalMutex.Unlock() - - var err error - switch j.JobConfig.Type { - case Cmd: - err = j.runCmd(jobLogFile) - case Sql: - err = j.runSql(jobLogFile) - } - if err != nil { - j.Status = Error - log.Error(err.Error()) - - globalMutex.Lock() - j.LastError = err.Error() - globalMutex.Unlock() - } else { - j.Status = Inactive - globalMutex.Lock() - j.LastError = "" - globalMutex.Unlock() - } - - endTime := time.Now() - log.Infof("Finished (%s).", endTime.Sub(startTime).Truncate(time.Second).String()) - - globalMutex.Lock() - j.CurrentRunningCount-- - j.LastEndTime = endTime.Format(config.TimeFormat) - j.LastExecutionDuration = endTime.Sub(startTime).Truncate(time.Second).String() - globalMutex.Unlock() - + err := j.runTry(log, jobLogFile) if err == nil { break } @@ -179,6 +141,49 @@ func (j *Job) Run() { } } +func (j *Job) runTry(log *log.Entry, jobLogFile *os.File) error { + log.Info("Started.") + startTime := time.Now() + + globalMutex.Lock() + j.CurrentRunningCount++ + j.Status = Running + j.LastStartTime = startTime.Format(config.TimeFormat) + globalMutex.Unlock() + + var err error + switch j.JobConfig.Type { + case Cmd: + err = j.runCmd(jobLogFile) + case Sql: + err = j.runSql(jobLogFile) + } + if err != nil { + j.Status = Error + log.Error(err.Error()) + + globalMutex.Lock() + j.LastError = err.Error() + globalMutex.Unlock() + } else { + j.Status = Inactive + globalMutex.Lock() + j.LastError = "" + globalMutex.Unlock() + } + + endTime := time.Now() + log.Infof("Finished (%s).", endTime.Sub(startTime).Truncate(time.Second).String()) + + globalMutex.Lock() + j.CurrentRunningCount-- + j.LastEndTime = endTime.Format(config.TimeFormat) + j.LastExecutionDuration = endTime.Sub(startTime).Truncate(time.Second).String() + globalMutex.Unlock() + + return err +} + func (j *Job) runCmd(jobLogFile *os.File) error { command, params := j.commandAndParams()