-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
66 lines (61 loc) · 1.83 KB
/
run.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 tasks
import (
"context"
"github.com/farseer-go/fs/container"
"github.com/farseer-go/fs/exception"
"github.com/farseer-go/fs/flog"
"github.com/farseer-go/fs/stopwatch"
"github.com/farseer-go/fs/trace"
"time"
)
// Run 运行一个任务,运行前先休眠
// interval:任务运行的间隔时间
// taskFn:要运行的任务
func Run(taskName string, interval time.Duration, taskFn func(context *TaskContext), ctx context.Context) {
// 不立即运行,则先休眠interval时间
if interval <= 0 {
panic("interval参数,必须大于0")
}
go func() {
taskInterval := interval
for {
select {
case <-ctx.Done():
return
case <-time.After(taskInterval):
taskInterval = runTask(taskName, interval, taskFn)
}
}
}()
}
// RunNow 运行一个任务
// interval:任务运行的间隔时间
// taskFn:要运行的任务
func RunNow(taskName string, interval time.Duration, taskFn func(context *TaskContext), ctx context.Context) {
// 立即执行
taskFn(&TaskContext{
sw: stopwatch.StartNew(),
})
Run(taskName,interval,taskFn,ctx)
}
// 运行任务
func runTask(taskName string, interval time.Duration, taskFn func(context *TaskContext)) (nextInterval time.Duration) {
// 这里需要提前设置默认的间隔时间。如果发生异常时,不提前设置会=0
nextInterval = interval
entryTask := container.Resolve[trace.IManager]().EntryTask(taskName)
try := exception.Try(func() {
taskContext := &TaskContext{
sw: stopwatch.StartNew(),
}
taskFn(taskContext)
flog.ComponentInfof("task", "%s,耗时:%s", taskName, taskContext.sw.GetMillisecondsText())
if taskContext.nextRunAt.Year() >= 2022 {
nextInterval = taskContext.nextRunAt.Sub(time.Now())
}
})
try.CatchException(func(exp any) {
entryTask.Error(flog.Errorf("[%s] throw exception:%s", taskName, exp))
})
entryTask.End()
return
}