2018-03-07 18:29:53 +01:00
|
|
|
package clocksmith
|
|
|
|
|
|
|
|
import "time"
|
|
|
|
|
|
|
|
const (
|
|
|
|
// DefaultGranularity - Maximum duration of actual time.Sleep() calls
|
2018-03-07 19:00:09 +01:00
|
|
|
DefaultGranularity = 5 * time.Second
|
2018-03-07 18:29:53 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// SleepWithGranularity - sleeps for the given amount of time, with the given granularity;
|
|
|
|
// doesn't pause if the system goes to hibernation
|
|
|
|
func SleepWithGranularity(duration time.Duration, granularity time.Duration) {
|
|
|
|
if duration <= granularity {
|
|
|
|
time.Sleep(duration)
|
|
|
|
return
|
|
|
|
}
|
2018-03-07 18:51:55 +01:00
|
|
|
start := time.Now().Unix()
|
2018-03-07 18:29:53 +01:00
|
|
|
for {
|
|
|
|
time.Sleep(granularity)
|
2018-03-07 18:51:55 +01:00
|
|
|
elapsed := time.Duration(time.Now().Unix()-start) * time.Second
|
|
|
|
if elapsed < 0 || elapsed > duration {
|
|
|
|
break
|
|
|
|
} else if elapsed > duration-granularity {
|
2018-03-07 18:29:53 +01:00
|
|
|
time.Sleep(duration - elapsed)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sleep - sleeps for the given amount of time, with the default granularity;
|
|
|
|
// doesn't pause if the system goes to hibernation
|
|
|
|
func Sleep(duration time.Duration) {
|
|
|
|
SleepWithGranularity(duration, DefaultGranularity)
|
|
|
|
}
|