-
Notifications
You must be signed in to change notification settings - Fork 12
/
task.go
91 lines (80 loc) · 1.64 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
89
90
91
// Copyright 2020 The searKing Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package resilience
import (
"context"
"fmt"
"strings"
"time"
)
type TaskType struct {
Drop bool // task will be dropped
Retry bool // task will be retried if error happens
Construct bool // task will be called after New
Repeat bool // Task will be executed again and again
}
func (t TaskType) String() string {
var b strings.Builder
if t.Drop {
b.WriteString("drop")
}
if t.Retry {
if b.String() != "" {
b.WriteRune('-')
}
b.WriteString("retry")
}
if t.Construct {
if b.String() != "" {
b.WriteRune('-')
}
b.WriteString("construct")
}
if t.Repeat {
if b.String() != "" {
b.WriteRune('-')
}
b.WriteString("repeat")
}
return b.String()
}
type Task struct {
Type TaskType
State TaskState
Description string // for debug
Handle func() error
RepeatDuration time.Duration
RetryDuration time.Duration
Ctx context.Context
CancelFn context.CancelFunc
inShutdown bool
}
//
// The returned context is always non-nil; it defaults to the
// background context.
func (t *Task) Context() context.Context {
if t.Ctx != nil {
return t.Ctx
}
return context.Background()
}
func (t *Task) String() string {
if t == nil {
return "empty task"
}
return fmt.Sprintf("%s-%s-%s", t.ID(), t.State, t.Description)
}
func (t *Task) ID() string {
if t == nil {
return "empty task"
}
return fmt.Sprintf("%s-%p", t.Type, t.Handle)
}
func (t *Task) Clone() *Task {
if t == nil {
return nil
}
task := *t
return &task
}