-
Notifications
You must be signed in to change notification settings - Fork 1
/
timer.go
71 lines (56 loc) · 1.2 KB
/
timer.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
60
61
62
63
64
65
66
67
68
69
70
71
package timers
import (
"sync"
"time"
)
// 延时执行函数,不阻塞当前进程
func Delay(duration time.Duration, task func(timer *time.Timer)) *time.Timer {
timer := time.NewTimer(duration)
go func() {
<-timer.C
task(timer)
}()
return timer
}
// 在某个时间点执行函数,不阻塞当前进程
func At(atTime time.Time, task func(timer *time.Timer)) *time.Timer {
timer := time.NewTimer(-time.Since(atTime))
go func() {
<-timer.C
task(timer)
}()
return timer
}
// 每隔一段时间执行函数,不阻塞当前进程
func Every(duration time.Duration, task func(ticker *time.Ticker)) *time.Ticker {
ticker := time.NewTicker(duration)
go func() {
for range ticker.C {
task(ticker)
}
}()
return ticker
}
// 循环执行某个函数,并保持每次执行之间的间隔
func Loop(duration time.Duration, task func(looper *Looper)) *Looper {
wg := &sync.WaitGroup{}
wg.Add(1)
looper := NewLooper()
looper.wg = wg
go func() {
defer wg.Add(-1)
for {
if looper.isStopping {
looper.isStopping = false
return
}
task(looper)
if looper.isStopping {
looper.isStopping = false
return
}
time.Sleep(duration)
}
}()
return looper
}