forked from go-co-op/gocron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.go
101 lines (88 loc) · 2.12 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
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
package gocron
import (
"context"
"sync"
"golang.org/x/sync/semaphore"
)
const (
// default is that if a limit on maximum concurrent jobs is set
// and the limit is reached, a job will skip it's run and try
// again on the next occurrence in the schedule
RescheduleMode limitMode = iota
// in wait mode 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.
//
// Note: this mode can produce unpredictable results as
// job execution order isn't guaranteed. For example, a job that
// executes frequently may pile up in the wait queue and be executed
// many times back to back when the queue opens.
WaitMode
)
type executor struct {
jobFunctions chan jobFunction
stop chan struct{}
limitMode limitMode
maxRunningJobs *semaphore.Weighted
}
func newExecutor() executor {
return executor{
jobFunctions: make(chan jobFunction, 1),
stop: make(chan struct{}, 1),
}
}
func (e *executor) start() {
wg := sync.WaitGroup{}
stopCtx, cancel := context.WithCancel(context.Background())
for {
select {
case f := <-e.jobFunctions:
wg.Add(1)
go func() {
defer wg.Done()
if e.maxRunningJobs != nil {
if !e.maxRunningJobs.TryAcquire(1) {
switch e.limitMode {
case RescheduleMode:
return
case WaitMode:
for {
select {
case <-stopCtx.Done():
return
case <-f.ctx.Done():
return
default:
}
if e.maxRunningJobs.TryAcquire(1) {
break
}
}
}
}
defer e.maxRunningJobs.Release(1)
}
switch f.runConfig.mode {
case defaultMode:
callJobFuncWithParams(f.function, f.parameters)
case singletonMode:
_, _, _ = f.limiter.Do("main", func() (interface{}, error) {
select {
case <-stopCtx.Done():
return nil, nil
case <-f.ctx.Done():
return nil, nil
default:
}
callJobFuncWithParams(f.function, f.parameters)
return nil, nil
})
}
}()
case <-e.stop:
cancel()
wg.Wait()
return
}
}
}