MCPcopy Create free account
hub / github.com/astercloud/aster / StartTask

Method StartTask

pkg/tools/builtin/task_manager.go:107–202  ·  view source on GitHub ↗

StartTask 启动后台任务

(ctx context.Context, cmd string, opts *TaskOptions)

Source from the content-addressed store, hash-verified

105
106// StartTask 启动后台任务
107func (tm *FileTaskManager) StartTask(ctx context.Context, cmd string, opts *TaskOptions) (*TaskInfo, error) {
108 tm.mu.Lock()
109 defer tm.mu.Unlock()
110
111 // 生成任务ID
112 taskID := fmt.Sprintf("task_%d", time.Now().UnixNano())
113
114 // 设置默认选项
115 if opts == nil {
116 opts = &TaskOptions{
117 Timeout: 30 * time.Minute,
118 Background: true,
119 Shell: "bash",
120 CaptureOutput: true,
121 OutputDir: tm.outputDir,
122 }
123 }
124
125 if opts.OutputDir == "" {
126 opts.OutputDir = tm.outputDir
127 }
128
129 // 创建任务信息
130 taskInfo := &TaskInfo{
131 ID: taskID,
132 Command: cmd,
133 Status: "starting",
134 StartTime: time.Now(),
135 WorkDir: opts.WorkDir,
136 Shell: opts.Shell,
137 Options: opts,
138 Metadata: make(map[string]string),
139 LastUpdate: time.Now(),
140 }
141
142 // 构建命令
143 fullCmd := tm.buildCommand(cmd, opts)
144
145 // 启动命令
146 cmdObj := exec.CommandContext(ctx, "bash", "-c", fullCmd)
147 cmdObj.Dir = opts.WorkDir
148
149 // 设置环境变量
150 if len(opts.Env) > 0 {
151 env := os.Environ()
152 for k, v := range opts.Env {
153 env = append(env, fmt.Sprintf("%s=%s", k, v))
154 }
155 cmdObj.Env = env
156 }
157
158 // 创建输出文件
159 outputFile := filepath.Join(opts.OutputDir, taskID+".stdout")
160 errorFile := filepath.Join(opts.OutputDir, taskID+".stderr")
161
162 if opts.CaptureOutput {
163 outFile, err := os.Create(outputFile)
164 if err != nil {

Callers

nothing calls this directly

Calls 7

buildCommandMethod · 0.95
saveTaskMethod · 0.95
monitorTaskMethod · 0.95
CreateMethod · 0.65
CloseMethod · 0.65
StartMethod · 0.65
JoinMethod · 0.45

Tested by

no test coverage detected