From 6e8622e4f347eb5b46183d5bc6f2c1c9f5e86582 Mon Sep 17 00:00:00 2001 From: ouqiang Date: Sat, 5 Aug 2017 23:05:33 +0800 Subject: [PATCH] =?UTF-8?q?feat($task):=20=E6=9B=BF=E6=8D=A2=E5=AD=90?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1=E5=91=BD=E4=BB=A4=E4=B8=AD=E7=9A=84=E9=A2=84?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=E5=8D=A0=E4=BD=8D=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 子任务可根据主任务执行结果执行相应操作, 如主任务执行失败发送短信. 占位符{{.Code}}, {{.Message}} --- service/task.go | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/service/task.go b/service/task.go index 238f153..846acfe 100644 --- a/service/task.go +++ b/service/task.go @@ -14,6 +14,8 @@ import ( rpcClient "github.com/ouqiang/gocron/modules/rpc/client" pb "github.com/ouqiang/gocron/modules/rpc/proto" "strings" + "text/template" + "bytes" ) // 定时任务调度管理器 @@ -316,14 +318,41 @@ func execDependencyTask(taskModel models.TaskHost, taskResult TaskResult) { if len(tasks) == 0 { logger.Errorf("依赖任务列表为空#主任务ID-%d", taskModel.Id) } - serviceTask := new(Task) for _, task := range tasks { + task.Command = appendResultToCommand(task.Command, taskResult) task.Spec = fmt.Sprintf("依赖任务(主任务ID-%d)", taskModel.Id) serviceTask.Run(task) } } +/** + * 添加主任务执行结果到子任务命令中, 占位符{{.Code}} {{.Message}} + */ +func appendResultToCommand(command string, taskResult TaskResult) string { + var code int8 = 0 + if taskResult.Err != nil { + code = 1 + } + data := map[string]interface{} { + "Code": code, + "Message": taskResult.Result, + } + var buf *bytes.Buffer = new(bytes.Buffer) + tmpl, err := template.New("command").Parse(command) + if err != nil { + logger.Errorf("替换子任务命令占位符失败#%s", err.Error()) + return command + } + err = tmpl.Execute(buf, data) + if err != nil { + logger.Errorf("替换子任务命令占位符失败#%s", err.Error()) + return command + } + + return buf.String() +} + // 发送任务结果通知 func SendNotification(taskModel models.TaskHost, taskResult TaskResult) { var statusName string