-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.go
103 lines (84 loc) · 1.8 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
package workers
import (
"context"
"sync"
"github.com/google/uuid"
)
type simpleJob struct {
id string
jobFunc SimpleJobFunc
params []interface{}
status Status
statusLock sync.RWMutex
doneChan chan ChanSignal
ctxJobFunc context.Context
cancelJobFuncLock sync.RWMutex
cancelJobFunc context.CancelFunc
}
type SimpleJobFunc func(ctx context.Context, jobId string, params ...interface{})
func NewJobSimple(
jobFunc SimpleJobFunc, params ...interface{},
) Job {
return &simpleJob{
id: uuid.NewString(),
jobFunc: jobFunc,
params: params,
status: StatusCreated,
doneChan: make(chan ChanSignal),
}
}
func (s *simpleJob) Id() string {
return s.id
}
func (s *simpleJob) Do(ctx context.Context) {
if s.Status() != StatusCreated {
return
}
s.setStatus(StatusRunning)
defer s.setStatus(StatusStopped)
s.cancelJobFuncLock.Lock()
s.ctxJobFunc, s.cancelJobFunc = context.WithCancel(ctx)
s.cancelJobFuncLock.Unlock()
defer func() {
s.cancelJobFuncLock.RLock()
if s.cancelJobFunc != nil {
s.cancelJobFunc()
}
s.cancelJobFuncLock.RUnlock()
}()
go func(ctx context.Context) {
s.jobFunc(ctx, s.id, s.params...)
close(s.doneChan)
}(s.ctxJobFunc)
select {
case <-s.doneChan:
case <-ctx.Done():
}
}
func (s *simpleJob) Cancel(ctx context.Context) {
if s.Status() != StatusRunning {
return
}
select {
case <-s.doneChan:
case <-ctx.Done():
s.cancelJobFuncLock.RLock()
if s.cancelJobFunc != nil {
s.cancelJobFunc()
}
s.cancelJobFuncLock.RUnlock()
}
}
func (s *simpleJob) Status() Status {
s.statusLock.RLock()
defer s.statusLock.RUnlock()
return s.status
}
func (s *simpleJob) Done() chan ChanSignal {
return s.doneChan
}
func (s *simpleJob) setStatus(status Status) {
s.statusLock.Lock()
defer s.statusLock.Unlock()
s.status = status
}