StartTask 启动后台任务
(ctx context.Context, cmd string, opts *TaskOptions)
| 105 | |
| 106 | // StartTask 启动后台任务 |
| 107 | func (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 { |
nothing calls this directly
no test coverage detected