Created
August 12, 2017 14:34
-
-
Save machiel/f07ff7d0ff8024161e44220b1363f04a to your computer and use it in GitHub Desktop.
Run task at specific time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
interval := time.Second * 5 | |
fmt.Println("Starting at:", utc()) | |
for { | |
time.Sleep(calculateDurationUntilNext(interval)) | |
// Let's assumet his task takes 2 seconds | |
fmt.Println(utc()) | |
time.Sleep(time.Second * 2) | |
} | |
} | |
func calculateDurationUntilNext(interval time.Duration) time.Duration { | |
return utc().Truncate(interval).Add(interval).Sub(utc()) | |
} | |
func utc() time.Time { | |
return time.Now().UTC() | |
} | |
// Example output: | |
// Starting at: 2017-08-12 14:32:43.377570185 +0000 UTC | |
// 2017-08-12 14:32:45.000228571 +0000 UTC | |
// 2017-08-12 14:32:50.000234413 +0000 UTC | |
// 2017-08-12 14:32:55.000214206 +0000 UTC | |
// If tasks takes longer than interval, for example 6 seconds: | |
// Starting at: 2017-08-12 14:33:44.819856064 +0000 UTC | |
// 2017-08-12 14:33:45.000197675 +0000 UTC | |
// 2017-08-12 14:33:55.000429476 +0000 UTC | |
// 2017-08-12 14:34:05.000239421 +0000 UTC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment