forked from pcelvng/task
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
66 lines (54 loc) · 1.5 KB
/
worker.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
package task
import (
"context"
"fmt"
)
// NewWorker is a worker initializer called by the Launcher to
// generate a new worker for a new task.
type NewWorker func(info string) Worker
type Worker interface {
// DoTask will return a Result and msg string.
DoTask(context.Context) (Result, string)
}
// IsDone is a helper function that determines if ctx has been canceled
func IsDone(ctx context.Context) bool {
select {
case <-ctx.Done():
return true
default:
return false
}
}
// Interrupted is a helper function that can be called when DoTask was interrupted
func Interrupted() (Result, string) {
return ErrResult, "task interrupted"
}
// Completed is a helper function that can be called when DoTask has completed
func Completed(format string, a ...interface{}) (Result, string) {
return CompleteResult, fmt.Sprintf(format, a...)
}
func Failed(err error) (Result, string) {
return ErrResult, err.Error()
}
func Failf(format string, a ...interface{}) (Result, string) {
return ErrResult, fmt.Sprintf(format, a...)
}
// InvalidWorker is a helper function to indicate an error when calling MakerWorker
func InvalidWorker(format string, a ...interface{}) Worker {
return &invalidWorker{
message: fmt.Sprintf(format, a...),
}
}
type invalidWorker struct {
message string
}
func (w *invalidWorker) DoTask(_ context.Context) (Result, string) {
return ErrResult, w.message
}
func IsInvalidWorker(w Worker) (bool, string) {
i, ok := w.(*invalidWorker)
if ok {
return true, i.message
}
return false, ""
}