I have four separate instances of a server running and I want only one of them to run a query every 5 seconds. The problem I am having is that they seem to be able to check the redis key that i have set for the last time the query was run so quickly that multiple instances run my query at the same time.
Im using a package cron for go:
c.AddFunc(config.CronInterval, func() {
KeyExpired(redisClient, cronInterval)
})
c.Start()
Here is my KeyExpired func
var CronInterval = "@every 5s"
func KeyExpired(redisClient *redis.Client, cronInterval time.Duration) bool {
//Convert the duration in the config to seconds
cronIntervalSeconds := int64(cronInterval.Seconds())
//Get the last value that was set as reporting time
rval := redisClient.Get("StatReporting")
if rval.Err() != nil {
redisClient.Set("StatReporting", time.Now().UTC().Format(timeFormat), 0)
return false
}
lastRun, err := time.Parse(timeFormat, rval.Val())
if err != nil {
log.Error(err.Error())
redisClient.Set("StatReporting", time.Now().UTC().Format(timeFormat), 0)
return false
}
if (time.Now().UTC().Unix() - lastRun.UTC().Unix()) >= cronIntervalSeconds {
fmt.Println(config.Port, time.Now().UTC().Unix())
redisClient.Set("StatReporting", time.Now().Add(time.Second).UTC().Format(timeFormat), 0)
return true
} else {
fmt.Println(config.Port, "WAITING")
return false
}
}
And here is the output with 4 instances running:
5559 1516551859
5558 1516551859
5777 WAITING
9999 WAITING
5559 WAITING
5558 WAITING
5777 1516551865
9999 WAITING
5559 WAITING
5558 WAITING
5777 WAITING
9999 1516551872
5559 WAITING
5558 WAITING
5777 WAITING
9999 WAITING
5558 1516551879
5559 1516551879
5777 WAITING
9999 WAITING
5559 WAITING
5558 WAITING
5777 1516551885
9999 WAITING
5558 WAITING
5559 WAITING
5777 WAITING