-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask.go
87 lines (69 loc) · 1.93 KB
/
task.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
package go_scheduler
import (
"context"
"github.com/oklog/run"
)
// TaskFunc describes the signature of a task function.
type TaskFunc = func(ctx context.Context) error
// Task wraps a task function.
type Task struct {
scheduler *Scheduler
function TaskFunc
}
func newTask(scheduler *Scheduler, function TaskFunc) *Task {
return &Task{
scheduler: scheduler,
function: function,
}
}
// Dependencies lists the tasks the this task depends on.
func (t *Task) Dependencies() []*Task {
return t.scheduler.Dependencies(t)
}
// DependencyCount returns the number of tasks this task depends on.
func (t *Task) DependencyCount() int {
return t.scheduler.DependencyCount(t)
}
// DependsOn creates a dependency between this task and the dependency task.
// When ran, the scheduler ensures the dependency task is executed first.
func (t *Task) DependsOn(dependency *Task) {
t.scheduler.AddDependency(t, dependency)
}
// RemoveDependency removes the dependency between this task and the dependency task.
func (t *Task) RemoveDependency(dependency *Task) {
t.scheduler.RemoveDependency(t, dependency)
}
// Run executes the task.
func (t *Task) Run(ctx context.Context) error {
return t.function(ctx)
}
type taskRunner struct {
}
func newTaskRunner() *taskRunner {
return &taskRunner{}
}
func (r *taskRunner) Run(ctx context.Context, tasks []*Task) error {
var g run.Group
ctx, cancel := context.WithCancel(ctx)
for i := range tasks {
task := tasks[i]
g.Add(func() error {
return task.Run(ctx)
}, func(error) {
cancel()
})
}
return g.Run()
}
// Options holds the scheduler's configuration.
type Options struct {
ConcurrentTasks int
}
// Option describes a function which mutates the scheduler's configuration.
type Option func(*Options)
// ConcurrentTasks sets the maximum number of tasks to run at any given time.
func ConcurrentTasks(maximum int) Option {
return func(options *Options) {
options.ConcurrentTasks = maximum
}
}