-
Notifications
You must be signed in to change notification settings - Fork 2
/
task.go
88 lines (75 loc) · 1.38 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
88
package YouTubeDownloader
import (
"os"
"fmt"
"context"
"path/filepath"
)
type Task struct {
Context context.Context
CancelFunc context.CancelFunc
Uuid string
Tmpdir string
PreCancelFuncs []func()
PostCancelFuncs []func()
}
func (Task *Task) Done() {
for _, f := range Task.PreCancelFuncs {
f()
}
Task.CancelFunc()
for _, f := range Task.PostCancelFuncs {
f()
}
}
func (Task *Task) Abort() {
for _, f := range Task.PreCancelFuncs {
f()
}
Task.CancelFunc()
for _, f := range Task.PostCancelFuncs {
f()
}
}
func NewTask(uuid string) *Task {
ctx, cancel := context.WithCancel(context.Background())
task_tmpdir := filepath.Join(tmpdir, uuid)
os.MkdirAll(task_tmpdir, 0o755)
return &Task{
ctx,
cancel,
uuid,
task_tmpdir,
[]func(){},
[]func(){
func(){os.RemoveAll(task_tmpdir)},
},
}
}
///////////////////////////////////////
type Tasks map[string]*Task
func (Tasks Tasks) New(uuid string) *Task {
Tasks[uuid] = NewTask(uuid)
return Tasks[uuid]
}
func (Tasks Tasks) Done(uuid string) error {
task, ok := Tasks[uuid]
if ok != true {
return fmt.Errorf("task does not exist")
}
task.Done()
delete(Tasks, uuid)
return nil
}
func (Tasks Tasks) Abort(uuid string) error {
task, ok := Tasks[uuid]
if ok != true {
return fmt.Errorf("task does not exist")
}
task.Abort()
delete(Tasks, uuid)
return nil
}
func NewTasks() Tasks {
return make(Tasks)
}