From a7552c210d5c63cb400ab417c752298756066fa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Thu, 23 Jun 2022 16:46:22 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BB=BB=E5=8A=A1=E8=BF=90?= =?UTF-8?q?=E8=A1=8C=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- abstract.go | 2 ++ define.go | 4 ---- task.go | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/abstract.go b/abstract.go index 2b7b5b0..e2d419c 100644 --- a/abstract.go +++ b/abstract.go @@ -19,6 +19,8 @@ type ITask interface { Name() string // Description 任务描述 Description() string + // GetRunID 获取任务ID + GetRunID() string // Callback 任务执行的回调 Callback(result *Result) error // Execute 执行任务 diff --git a/define.go b/define.go index 72e7089..873c790 100644 --- a/define.go +++ b/define.go @@ -15,8 +15,6 @@ package task type Config struct { // TaskName 执行的任务名称 TaskName string - // GetRunID 获取任务运行的ID - GetRunID func() string // Async 是否异步运行 Async bool // Timeout 单位 : 秒, <= 0认为不设置超时 @@ -39,8 +37,6 @@ type Result struct { TaskRunID string // 任务运行ID TaskDescription string // 任务描述 TaskConfig *Config // 任务配置 - Async bool // 是否异步 - Param map[string]interface{} // 任务参数 Data map[string]interface{} // 任务结果数据 Err error // 异常信息, err == nil , 代表执行成功 } diff --git a/task.go b/task.go index f0bdaaf..05725f1 100644 --- a/task.go +++ b/task.go @@ -10,7 +10,9 @@ package task import ( "context" "fmt" + "runtime" "sync" + "time" ) var ( @@ -76,6 +78,47 @@ func (d *dispatch) Remove(taskNameList ...string) error { // Author : go_developer@163.com<白茶清欢> // // Date : 15:18 2022/6/23 -func (d *dispatch) Run(ctx context.Context, cfg *Config, taskParam map[string]interface{}) (map[string]interface{}, error) { - return nil, nil +func (d *dispatch) Run(ctx context.Context, cfg *Config) *Result { + var ( + taskInstance ITask + exist bool + ) + + result := &Result{ + StartTime: time.Now().UnixNano(), + FinishTime: 0, + Used: 0, + TaskRunID: "", + TaskDescription: "", + TaskConfig: cfg, + Data: nil, + Err: nil, + } + defer func() { + result.FinishTime = time.Now().UnixNano() + result.Used = result.FinishTime - result.StartTime + if e := recover(); nil != e { + switch e.(type) { + case runtime.Error: // 运行时错误 + result.Err = fmt.Errorf("出现运行时Panic : %v", e) + default: // 非运行时错误 + result.Err = fmt.Errorf("出现其他场景Panic : %v", e) + } + } + }() + d.lock.RLock() + if taskInstance, exist = d.taskTable[cfg.TaskName]; !exist { + result.Err = fmt.Errorf("%v 任务未注册", cfg.TaskName) + } + result.TaskRunID = taskInstance.GetRunID() + result.TaskDescription = taskInstance.Description() + if cfg.Async { + // 异步运行 + go func() { + result.Data, result.Err = taskInstance.Execute(ctx, cfg) + }() + } else { + result.Data, result.Err = taskInstance.Execute(ctx, cfg) + } + return result }