File: clocksmith.go

package info (click to toggle)
golang-github-jedisct1-go-clocksmith 0.0~git20250224.e151f21-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 68 kB
  • sloc: makefile: 2
file content (34 lines) | stat: -rw-r--r-- 936 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package clocksmith

import "time"

const (
	// DefaultGranularity - Maximum duration of actual time.Sleep() calls
	DefaultGranularity = 5 * time.Second
)

// 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
	}
	start := time.Now().Unix()
	for {
		time.Sleep(granularity)
		elapsed := time.Duration(time.Now().Unix()-start) * time.Second
		if elapsed < 0 || elapsed > duration {
			break
		} else if elapsed > duration-granularity {
			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)
}