-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcron.go
49 lines (41 loc) · 919 Bytes
/
cron.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
package gouse
import "time"
type ICronJob struct {
duration time.Duration
stopAfter time.Duration
callback func()
stopChan chan bool
}
func NewCronJob(duration, stopAfter time.Duration, callback func()) *ICronJob {
return &ICronJob{
duration: duration,
stopAfter: stopAfter,
callback: callback,
stopChan: make(chan bool),
}
}
func (cj *ICronJob) StartJob() {
go func() {
ticker := time.NewTicker(cj.duration)
stopTimer := time.NewTimer(cj.stopAfter)
defer ticker.Stop()
defer stopTimer.Stop()
for {
select {
case <-ticker.C:
cj.callback()
case <-stopTimer.C:
cj.stopChan <- true
return
}
}
}()
}
func (cj *ICronJob) WaitJob() {
<-cj.stopChan
}
func RunJob(duration, stopAfter uint64, callback func()) {
cronJob := NewCronJob(time.Duration(duration)*time.Second, time.Duration(stopAfter)*time.Second, callback)
cronJob.StartJob()
cronJob.WaitJob()
}