diff --git a/main.go b/main.go index e5e7bd1..b199af7 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,7 @@ import ( "fmt" "io/ioutil" "log" + "math" "os" "os/exec" "path" @@ -116,24 +117,23 @@ func getTime(timeString string) (int, int) { return int(hr), int(min) } -func getNextWait(config sunsetConfig) (int, int) { +func getNextWait(config sunsetConfig) time.Duration { index := nextIndex(config) now := time.Now() nextHr, nextMin := getTime(config.Files[index].Time) - var diffHr int - var diffMin int + // Today at the time + nextTime := time.Date(now.Year(), now.Month(), now.Day(), nextHr, nextMin, 0, 0, now.Location()) - // FIXME still not working - if now.Hour() >= nextHr && now.Minute() >= nextMin { - diffHr = 24 - (now.Hour() - nextHr) - diffMin = 60 - (now.Minute() - nextMin) - } else { - diffHr = nextHr - now.Hour() - diffMin = nextMin - now.Minute() + until := nextTime.Sub(now) + + if math.Floor(until.Minutes()) > 0 { + return until } - return diffHr, diffMin + // Next day the the time + nextTime = nextTime.AddDate(0, 0, 1) + return nextTime.Sub(now) } func currentImage(configPath string, config sunsetConfig) string { @@ -149,8 +149,8 @@ func block(configPath string, config sunsetConfig, command string) { image := currentImage(configPath, config) go runCommand(command, image) for { - nextHr, nextMin := getNextWait(config) - timer := time.NewTimer((time.Duration(nextHr) * time.Hour) + (time.Duration(nextMin) * time.Minute)) + until := getNextWait(config) + timer := time.NewTimer(until) <-timer.C log.Printf("Running command: %s\n", command) image := currentImage(configPath, config) @@ -179,8 +179,8 @@ func main() { if *printNextTime { fmt.Printf("%s", getNextTime(conf)) } else if *printNextWait { - hr, min := getNextWait(conf) - fmt.Printf("%dh%dm", hr, min) + unitl := getNextWait(conf) + fmt.Printf("%s", unitl) } else if *blockFlag { if *blockCommand == "" {