-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop.go
More file actions
48 lines (41 loc) · 1.25 KB
/
loop.go
File metadata and controls
48 lines (41 loc) · 1.25 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package portal
import (
"time"
)
// Rate converts a frequency in hertz to a time duration.
func Rate(hz int) time.Duration {
return time.Second / time.Duration(hz)
}
// RatePrecise converts a frequency in hertz to a time duration with the highest precision that Go can muster.
func RatePrecise(hz float64) time.Duration {
return time.Second / time.Duration(hz)
}
// Loop runs a thread with a minimum granularity in timing, optionally detaching into goroutines.
func Loop(granularity *time.Duration, detach bool, fnc func()) (stopper chan bool, lastLoop *time.Time) {
stopper = make(chan bool)
now := time.Now()
loopThread(stopper, granularity, detach, &now, fnc)
return stopper, &now
}
func loopThread(stopper chan bool, granularity *time.Duration, detach bool, lastLoop *time.Time, fnc func()) {
go func(stopper chan bool, granularity *time.Duration, lastLoop *time.Time, fnc func()) {
for {
if detach {
go fnc()
} else {
fnc()
}
if since := time.Since(*lastLoop); since < *granularity {
rest := *granularity - since
time.Sleep(rest)
*lastLoop = time.Now()
}
select {
case <-stopper:
close(stopper)
return
default:
}
}
}(stopper, granularity, lastLoop, fnc)
}