forked from Sagleft/simple-cron
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcron.go
More file actions
90 lines (75 loc) · 1.32 KB
/
cron.go
File metadata and controls
90 lines (75 loc) · 1.32 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
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
89
90
package simplecron
import (
"fmt"
"sync"
"time"
)
type CronObject struct {
timerTime time.Duration
callback func()
stopCh chan struct{}
stopWG sync.WaitGroup
active bool
paused bool
}
func NewCronHandler(callback func(), timerTime time.Duration) *CronObject {
return &CronObject{
timerTime: timerTime,
callback: callback,
stopCh: make(chan struct{}),
active: false,
paused: false,
}
}
func (c *CronObject) Stop() {
if c.active {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in Stop:", r)
}
}()
c.active = false
close(c.stopCh)
c.stopWG.Wait()
}
}
func (c *CronObject) Run(immediately ...bool) {
c.active = true
sleepAtStart := true
if len(immediately) > 0 && immediately[0] {
sleepAtStart = false
}
c.stopWG.Add(1)
go func() {
defer c.stopWG.Done()
if sleepAtStart {
select {
case <-time.After(c.timerTime):
case <-c.stopCh:
return
}
}
for c.active {
if !c.paused {
c.callback()
}
select {
case <-time.After(c.timerTime):
case <-c.stopCh:
return
}
}
}()
}
func (c *CronObject) IsActive() bool {
return c.active && !c.paused
}
func (c *CronObject) IsPaused() bool {
return c.paused
}
func (c *CronObject) Pause() {
c.paused = true
}
func (c *CronObject) Resume() {
c.paused = false
}