/
executor.go
73 lines (62 loc) · 1.32 KB
/
executor.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
package pointcron
import (
"context"
"sync"
"golang.org/x/sync/semaphore"
)
type executor struct {
jobFunctions chan jobFunction
stopCh chan struct{}
maxRunningJobs *semaphore.Weighted
}
func newExecutor() executor {
return executor{
jobFunctions: make(chan jobFunction, 1),
stopCh: make(chan struct{}, 1),
}
}
func (e *executor) start() {
stopCtx, cancel := context.WithCancel(context.Background())
runningJobsWg := sync.WaitGroup{}
for {
select {
case f := <-e.jobFunctions:
runningJobsWg.Add(1)
go func() {
defer runningJobsWg.Done()
if e.maxRunningJobs != nil {
if !e.maxRunningJobs.TryAcquire(1) {
// If a limit on maximum concurrent jobs is set
// and the limit is reached, a job will wait to try and run
// until a spot in the limit is freed up.
for {
select {
case <-stopCtx.Done():
return
case <-f.ctx.Done():
return
default:
}
if e.maxRunningJobs.TryAcquire(1) {
break
}
}
}
defer e.maxRunningJobs.Release(1)
}
f.setRunState(true)
callJobFunc(f.function)
f.setRunState(false)
}()
case <-e.stopCh:
cancel()
runningJobsWg.Wait()
e.stopCh <- struct{}{}
return
}
}
}
func (e *executor) stop() {
e.stopCh <- struct{}{}
<-e.stopCh
}