-
Notifications
You must be signed in to change notification settings - Fork 14
/
scheduler.go
119 lines (100 loc) · 2.2 KB
/
scheduler.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
package gitcollector
import (
"context"
"time"
"github.com/jpillora/backoff"
"gopkg.in/src-d/go-errors.v1"
)
var (
// ErrNewJobsNotFound must be returned by a JobScheduleFn when it can't
// find new Jobs.
ErrNewJobsNotFound = errors.NewKind(
"couldn't find new jobs to schedule")
// ErrJobSource must be returned by a JobScheduleFn when the source of
// job is closed.
ErrJobSource = errors.NewKind("job source is closed")
)
// JobScheduleFn is a function to schedule the next Job.
type JobScheduleFn func(context.Context) (Job, error)
type jobScheduler struct {
jobs chan Job
schedule JobScheduleFn
cancel chan struct{}
opts *WorkerPoolOpts
backoff *backoff.Backoff
}
const (
schedCapacity = 1000
schedTimeout = 5 * time.Second
// backoff default configuration
backoffMinDuration = 250 * time.Millisecond
backoffMaxDuration = 1024 * time.Second
backoffFactor = 2
backoffJitter = true
)
func newJobScheduler(
schedule JobScheduleFn,
opts *WorkerPoolOpts,
) *jobScheduler {
if opts.SchedulerCapacity <= 0 {
opts.SchedulerCapacity = schedCapacity
}
if opts.ScheduleJobTimeout <= 0 {
opts.ScheduleJobTimeout = schedTimeout
}
return &jobScheduler{
jobs: make(chan Job, opts.SchedulerCapacity),
schedule: schedule,
cancel: make(chan struct{}),
opts: opts,
backoff: &backoff.Backoff{
Min: backoffMinDuration,
Max: backoffMaxDuration,
Factor: backoffFactor,
Jitter: backoffJitter,
},
}
}
func (s *jobScheduler) finish() {
s.cancel <- struct{}{}
}
func (s *jobScheduler) Schedule() {
s.backoff.Reset()
for {
select {
case <-s.cancel:
return
default:
ctx, cancel := context.WithTimeout(
context.Background(),
s.opts.ScheduleJobTimeout,
)
defer cancel()
job, err := s.schedule(ctx)
if err != nil {
if ErrNewJobsNotFound.Is(err) {
if s.opts.NotWaitNewJobs {
continue
}
}
if ErrJobSource.Is(err) {
close(s.jobs)
return
}
select {
case <-s.cancel:
return
case <-time.After(s.backoff.Duration()):
}
continue
}
select {
case s.jobs <- job:
s.backoff.Reset()
s.opts.Metrics.Discover(job)
case <-s.cancel:
return
}
}
}
}