-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.go
288 lines (237 loc) · 6.01 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package yotei
import (
"context"
"fmt"
"io"
"iter"
"log/slog"
"math/rand"
"runtime"
"slices"
"sync"
)
// Scheduler is the main structure to handler
// task scheduling in yotei.
//
// Use [NewScheduler] to create a new scheduler.
type Scheduler struct {
workers uint64
tasks Tasks
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
logger *slog.Logger
mutex sync.Mutex
}
// WorkersNumCPUs uses the number of CPU cores of the computer.
// as the number of workers.
var (
// SingleWorker fires a scheduler with just one worker.
SingleWorker uint64 = 1
// NumCPUsWorkers fires a scheduler with [runtime.NumCPU] workers.
NumCPUsWorkers uint64 = uint64(runtime.NumCPU())
)
var (
// DefaultLogger is the default logger for the yotei scheduler.
DefaultLogger *slog.Logger = slog.Default()
// SilentLogger is a silent logger for the yotei scheduler.
SilentLogger *slog.Logger = slog.New(slog.NewTextHandler(io.Discard, nil))
)
// NewScheduler creates a new scheduler with the given workers and logger.
//
// If workers is `0` or [WorkersNumCPUs], the number of CPUs in the machine
// is used, as acording to [runtime.NumCPU].
//
// If the logger is `nil` or [DefaultLogger], the [slog.Default] will be used.
//
// # Example
//
// yotei.NewScheduler(
// yotei.WorkersNumCPUs,
// yotei.DefaultLogger,
// )
func NewScheduler(workers uint64, logger *slog.Logger) *Scheduler {
if workers == 0 {
workers = NumCPUsWorkers
}
if logger == nil {
logger = DefaultLogger
}
return &Scheduler{
workers: workers,
logger: logger,
}
}
// Add appends a task into the scheduler. If the task
// was already in the scheduler it will ignore it.
func (scheduler *Scheduler) Add(tasks ...Tasker) {
scheduler.mutex.Lock()
defer scheduler.mutex.Unlock()
for _, task := range tasks {
for _, t := range scheduler.tasks {
if t == task {
continue
}
}
scheduler.tasks = append(scheduler.tasks, task)
}
}
// Has returns true if the given task is currently
// in the scheduler.
func (scheduler *Scheduler) Has(task Tasker) bool {
scheduler.mutex.Lock()
defer scheduler.mutex.Unlock()
for _, t := range scheduler.tasks {
if t == task {
return true
}
}
return false
}
// Remove deletes the given tasks from the scheduler.
func (scheduler *Scheduler) Remove(tasks ...Tasker) {
scheduler.mutex.Lock()
defer scheduler.mutex.Unlock()
for i, t := range scheduler.tasks {
for _, task := range tasks {
if t == task {
scheduler.tasks = append(scheduler.tasks[:i], scheduler.tasks[i+1:]...)
}
}
}
}
func (scheduler *Scheduler) next() Tasker {
if !scheduler.mutex.TryLock() {
return nil
}
defer scheduler.mutex.Unlock()
tasks := scheduler.tasks.Unlocked()
weight := tasks.Weight()
if weight == 0 {
return nil
}
pick := rand.Uint64() % weight
current := uint64(0)
for _, task := range tasks {
current += task.Weight()
if pick < current {
if !task.IsConcurrent() {
task.Lock()
}
return task
}
}
return nil
}
func (scheduler *Scheduler) handle(ctx context.Context, task Tasker) {
if action := task.Handle(ctx); action != nil {
action(scheduler, task)
}
}
func (scheduler *Scheduler) handleTasker(task Tasker) {
defer func() {
if !task.IsConcurrent() {
task.Unlock()
}
}()
if duration := task.Duration(); duration > 0 {
ctx, cancel := context.WithTimeout(scheduler.ctx, duration)
defer cancel()
go scheduler.handle(ctx, task)
<-ctx.Done()
return
}
scheduler.handle(context.Background(), task)
}
func (scheduler *Scheduler) worker() {
defer scheduler.wg.Done()
for {
select {
case <-scheduler.ctx.Done():
return
default:
if task := scheduler.next(); task != nil {
scheduler.handleTasker(task)
continue
}
}
}
}
// Start begins executing the scheduler with the given set
// of tasks. If the scheduler was already running, it won't do anything.
//
// The scheduler spawns exactly [Scheduler.workers] workers, each in its own
// goroutine.
//
// If the task list contains no tasks to run (len == 0) no workers will be
// spawned, a warning will be emitted using the [Scheduler.logger] and
// the scheduler will remain in a running state.
func (scheduler *Scheduler) Start() {
if scheduler.IsRunning() {
return
}
scheduler.mutex.Lock()
defer scheduler.mutex.Unlock()
scheduler.ctx, scheduler.cancel = context.WithCancel(context.Background())
scheduler.logger.Info(
"starting scheduler",
"workers", scheduler.workers,
"tasks", len(scheduler.tasks),
)
if len(scheduler.tasks) == 0 {
scheduler.logger.Warn("no tasks to execute")
return
}
for i := uint64(0); i < scheduler.workers; i++ {
scheduler.wg.Add(1)
go scheduler.worker()
}
}
// Stop makes a running scheduler halt its execution.
// All the workers shut down gracefully, completing their
// current tasks.
//
// A call to [Scheduler.Stop] waits for all the workers
// to exit.
//
// If the scheduler was not running, this does nothing.
func (scheduler *Scheduler) Stop() {
if !scheduler.IsRunning() {
return
}
scheduler.mutex.Lock()
defer scheduler.mutex.Unlock()
scheduler.logger.Info("stopping scheduler")
scheduler.cancel()
scheduler.wg.Wait()
scheduler.tasks = nil
scheduler.ctx = nil
scheduler.cancel = nil
}
// IsRunning determines if the scheduler is
// currently running or not.
func (scheduler *Scheduler) IsRunning() bool {
scheduler.mutex.Lock()
defer scheduler.mutex.Unlock()
return scheduler.ctx != nil
}
// Snapshot returns the current scheduler tasks as an iterator.
//
// When creating the iterator, the actual tasks are freezed
// from the moment this function called to ensure it
// is concurrent safe.
func (scheduler *Scheduler) Snapshot() iter.Seq[Tasker] {
scheduler.mutex.Lock()
defer scheduler.mutex.Unlock()
return slices.Values(slices.Clone(scheduler.tasks))
}
// String returns a string representation of a scheduler.
func (scheduler *Scheduler) String() string {
scheduler.mutex.Lock()
defer scheduler.mutex.Unlock()
return fmt.Sprintf(
"Scheduler{is_running=%t, tasks=%s}",
scheduler.IsRunning(),
scheduler.tasks,
)
}