-
Notifications
You must be signed in to change notification settings - Fork 8
/
BatchJob.go
56 lines (46 loc) · 945 Bytes
/
BatchJob.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
package main
import "errors"
type BatchJob struct {
Job func()
runJob bool
done chan bool
}
func (batchJob *BatchJob) Start() error {
if batchJob.runJob {
return errors.New("error: can't stop not stopped job")
}
if batchJob.Job == nil {
return errors.New("error: empty job function")
}
if !batchJob.runJob {
batchJob.done = make(chan bool, 1)
}
go batchJob.execution(batchJob.done)
batchJob.runJob = true
return nil
}
func (batchJob *BatchJob) IsRunning() bool {
return batchJob.runJob
}
func (batchJob *BatchJob) Stop() error {
if !batchJob.runJob {
return errors.New("error: can't stop not stopted job")
}
batchJob.runJob = false
isDone := <-batchJob.done
if isDone {
close(batchJob.done)
return nil
}
return errors.New("error: failed stop job")
}
func (batchJob *BatchJob) execution(done chan bool) {
for {
if batchJob.runJob {
batchJob.Job()
} else {
done <- true
return
}
}
}