concurrentTasksExample 并发多任务示例
(ctx context.Context)
| 133 | |
| 134 | // concurrentTasksExample 并发多任务示例 |
| 135 | func concurrentTasksExample(ctx context.Context) { |
| 136 | executor := tools.NewLongRunningExecutor() |
| 137 | tool := NewMockDataProcessingTool(executor) |
| 138 | |
| 139 | // 启动多个任务 |
| 140 | taskIDs := make([]string, 5) |
| 141 | for i := range 5 { |
| 142 | taskID, _ := tool.StartAsync(ctx, map[string]any{ |
| 143 | "data_size": 100 * (i + 1), |
| 144 | "delay_ms": 200, |
| 145 | }) |
| 146 | taskIDs[i] = taskID |
| 147 | } |
| 148 | |
| 149 | fmt.Printf("✅ Started %d concurrent tasks\n", len(taskIDs)) |
| 150 | |
| 151 | // 等待所有任务完成 |
| 152 | for _, taskID := range taskIDs { |
| 153 | _, err := tools.WaitForCompletion(executor, taskID, 50*time.Millisecond, 5*time.Second) |
| 154 | if err != nil { |
| 155 | log.Printf("Task %s failed: %v", taskID, err) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // 列出所有任务 |
| 160 | allTasks := executor.ListTasks(nil) |
| 161 | completedTasks := executor.ListTasks(func(s *tools.TaskStatus) bool { |
| 162 | return s.State == tools.TaskStateCompleted |
| 163 | }) |
| 164 | |
| 165 | fmt.Printf("✅ All tasks: %d, Completed: %d\n", len(allTasks), len(completedTasks)) |
| 166 | } |
| 167 | |
| 168 | // cleanupExample 任务清理示例 |
| 169 | func cleanupExample(ctx context.Context) { |
no test coverage detected