-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
70 lines (54 loc) · 1.5 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
package cgscheduler
import (
"context"
"golang.org/x/sync/errgroup"
)
// 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 {
g, ctx := errgroup.WithContext(ctx)
for i := range tasks {
task := tasks[i]
g.Go(func() error {
return task.Run(ctx)
})
}
return g.Wait()
}