-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.go
127 lines (116 loc) · 2.07 KB
/
job.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package brook
import (
"errors"
"time"
)
type Job struct {
JobChan chan func()
PingChan chan string
Quit chan struct{}
Started bool
ticker *time.Ticker
job func()
jobArg func(...any)
}
func NewJob(job func()) *Job {
return &Job{
Quit: make(chan struct{}),
job: job,
}
}
func NewJobWithArgument(job func(...any)) *Job {
return &Job{
Quit: make(chan struct{}),
jobArg: job,
}
}
/* Uses a ticker as the job channel based on the interval */
func (j *Job) StartWithTicker(interval time.Duration) error {
if j.Started {
return startError()
}
j.ticker = time.NewTicker(interval)
go func() {
for {
select {
case <-j.ticker.C:
j.job()
case <-j.Quit:
// Not thread safe
j.ticker.Stop()
return
}
}
}()
j.Started = true
return nil
}
/* Uses a func channel as the job channel and does not use the job function given in the constructor*/
func (j *Job) StartWithChannel() error {
if j.Started {
return startError()
}
go func() {
for {
select {
case job := <-j.JobChan:
job()
case <-j.Quit:
return
}
}
}()
j.Started = true
return nil
}
/* Uses a string channel to get strings and executes the job function given in the constructor with the string value in the channel*/
func (j *Job) StartWithArgument() error {
if j.Started {
return startError()
}
go func() {
for {
select {
case s := <-j.PingChan:
j.jobArg(s)
case <-j.Quit:
return
}
}
}()
j.Started = true
return nil
}
/* Uses a string channel to get pinged and executes the job function given in the constructor*/
func (j *Job) Start() error {
if j.Started {
return startError()
}
go func() {
for {
select {
case <-j.PingChan:
j.job()
case <-j.Quit:
return
}
}
}()
j.Started = true
return nil
}
/* This stops all jobs */
func (j *Job) Stop() error {
if !j.Started {
return stopError()
}
close(j.Quit)
j.Started = false
return nil
}
func startError() error {
return errors.New("ERROR: Job already started")
}
func stopError() error {
return errors.New("ERROR: Job already stopped")
}