/
task.go
57 lines (46 loc) · 904 Bytes
/
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
package spider
import (
"context"
"fmt"
"sync"
"github.com/pkg/errors"
)
// Task is a task define
type Task struct {
ID uint64
TaskRule
TaskConfig
}
// NewTask return a new task object
func NewTask(id uint64, rule TaskRule, config TaskConfig) *Task {
return &Task{
ID: id,
TaskRule: rule,
TaskConfig: config,
}
}
var (
ctlMu = &sync.RWMutex{}
ctlMap = make(map[uint64]context.CancelFunc)
)
func addTaskCtrl(taskID uint64, cancelFunc context.CancelFunc) error {
ctlMu.Lock()
defer ctlMu.Unlock()
if _, ok := ctlMap[taskID]; ok {
return errors.WithStack(fmt.Errorf("duplicate taskID:%d", taskID))
}
ctlMap[taskID] = cancelFunc
return nil
}
// CancelTask cancel a task by taskID
func CancelTask(taskID uint64) bool {
ctlMu.Lock()
defer ctlMu.Unlock()
cancel, ok := ctlMap[taskID]
if !ok {
return false
}
cancel()
delete(ctlMap, taskID)
return true
}