/
task.go
94 lines (83 loc) · 2.09 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
92
93
94
package task
import (
"crypto/sha1"
"fmt"
"reflect"
"time"
sctx "github.com/appootb/substratum/v2/context"
ictx "github.com/appootb/substratum/v2/internal/context"
"github.com/appootb/substratum/v2/logger"
"github.com/appootb/substratum/v2/task"
"github.com/appootb/substratum/v2/util/scheduler"
"github.com/appootb/substratum/v2/util/timer"
)
const (
DebugLog = "_TASK_.debug"
ErrorLog = "_TASK_.error"
LogName = logger.LogTag + "name"
LogExecutor = logger.LogTag + "executor"
LogError = logger.LogTag + "error"
)
type Task struct{}
func (c *Task) Schedule(spec string, exec task.Executor, opts ...task.Option) error {
options := task.EmptyOptions()
for _, o := range opts {
o(options)
}
if options.Name == "" {
options.Name = fmt.Sprintf("%x", sha1.Sum([]byte(spec+c.reflectName(exec))))
}
schedule, err := scheduler.ParseStandard(spec)
if err != nil {
return err
}
go c.exec(schedule, exec, options)
return nil
}
func (c *Task) reflectName(exec task.Executor) string {
t := reflect.TypeOf(exec)
// reflect.Ptr's PkgPath and Name is empty
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return fmt.Sprintf("%s/%s", t.PkgPath(), t.Name())
}
func (c *Task) exec(schedule scheduler.Schedule, exec task.Executor, opts *task.Options) {
Reset:
ctx := ictx.Context
if opts.Singleton {
// Blocked before acquired the locker.
ctx = task.LockerImplementor().Lock(ctx, opts.Name)
}
for {
now := time.Now()
next := schedule.Next(now)
select {
case <-ctx.Done():
select {
case <-ictx.Context.Done():
if opts.Singleton {
task.LockerImplementor().Unlock(opts.Name)
}
return
default:
// Keep alive failed, reset.
goto Reset
}
case <-timer.After(next.Sub(now)):
err := exec.Execute(sctx.ServerContext(opts.Component), opts.Argument)
if err != nil {
logger.Error(ErrorLog, logger.Content{
LogError: err.Error(),
LogName: opts.Name,
LogExecutor: c.reflectName(exec),
})
} else {
logger.Debug(DebugLog, logger.Content{
LogName: opts.Name,
LogExecutor: c.reflectName(exec),
})
}
}
}
}