-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.go
88 lines (79 loc) · 1.97 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package commonUtils
import (
"errors"
"time"
)
type Function func()
func RunEveryDayAt(f Function, hour, minute, second, milisecond int) {
t := time.Now()
shoudRunAt := time.Date(t.Year(), t.Month(), t.Day(), hour, minute, second, milisecond, t.Location())
duration := time.Hour * 24
run(f, shoudRunAt, duration)
}
func RunEveryHourAt(f Function, minute, second, milisecond int) {
t := time.Now()
shoudRunAt := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), minute, second, milisecond, t.Location())
duration := time.Hour
run(f, shoudRunAt, duration)
}
func RunEveryMinuteAt(f Function, second, milisecond int) {
t := time.Now()
shoudRunAt := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), second, milisecond, t.Location())
duration := time.Minute
run(f, shoudRunAt, duration)
}
func run(f Function, shoudRunAt time.Time, duration time.Duration) {
gap := shoudRunAt.Sub(time.Now())
if gap < 0 {
shoudRunAt = shoudRunAt.Add(duration)
gap = shoudRunAt.Sub(time.Now()) // using time.Now() here to reduce the time difference to the minimum
}
for {
time.Sleep(gap)
gap = duration
f()
}
}
func RunEveryNMinute(f Function, n int64, runAtStart bool) {
duration := time.Minute * time.Duration(n)
if runAtStart {
f()
}
for {
time.Sleep(duration)
f()
}
}
func RunEveryNSecond(f Function, n int64, runAtStart bool) {
duration := time.Second * time.Duration(n)
if runAtStart {
f()
}
for {
time.Sleep(duration)
f()
}
}
func RunEvery(f Function, n int, timeUnit string, runAtStart bool) error {
var duration time.Duration
switch timeUnit {
case "Day":
duration = time.Hour * time.Duration(n*24)
case "Hour":
duration = time.Hour * time.Duration(n)
case "Minute":
duration = time.Minute * time.Duration(n)
case "Second":
duration = time.Second * time.Duration(n)
default:
return errors.New("timeUnit can only be one of 'Day', 'Hour', 'Minute', 'Second'.")
}
if runAtStart {
f()
}
for {
time.Sleep(duration)
f()
}
return nil
}