-
Notifications
You must be signed in to change notification settings - Fork 0
/
syncterval.go
59 lines (47 loc) · 1.24 KB
/
syncterval.go
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
49
50
51
52
53
54
55
56
57
58
59
package syncterval
import (
"time"
"github.com/alphadose/haxmap"
)
type funcInterval struct {
fn *func()
t int64
last int64
}
var funcIntervalListFast *haxmap.Map[uintptr, *funcInterval] = haxmap.New[uintptr, *funcInterval]()
var funcIntervalListSlow *haxmap.Map[uintptr, *funcInterval] = haxmap.New[uintptr, *funcInterval]()
func init(){
lastMin := int64(0)
go (func(){
for {
now := time.Now().UnixMilli()
funcIntervalListFast.ForEach(func(i uintptr, fnInterval *funcInterval) bool {
if now - fnInterval.last >= fnInterval.t {
fnInterval.last = now
(*fnInterval.fn)()
}
return true
})
if now - lastMin >= int64(time.Minute.Milliseconds()) {
lastMin = now
funcIntervalListSlow.ForEach(func(i uintptr, fnInterval *funcInterval) bool {
if now - fnInterval.last >= fnInterval.t {
fnInterval.last = now
(*fnInterval.fn)()
}
return true
})
}
time.Sleep(10 * time.Millisecond)
}
})()
}
func New(t time.Duration, fn func()){
fnRef := &fn
fnInterval := funcInterval{fnRef, int64(t.Milliseconds()), 0}
if t >= time.Minute {
funcIntervalListSlow.Set(funcIntervalListSlow.Len(), &fnInterval)
}else{
funcIntervalListFast.Set(funcIntervalListSlow.Len(), &fnInterval)
}
}