// 将任务提交到线程池中执行 CompletableFuture<?> future = CompletableFuture.runAsync(task, taskExecutor); taskFutures.put(taskId, future); future.thenAccept(result -> { // 更新任务状态为成功 taskInfo.setTaskStatus(StatusEnum.STATUS_SUCCESS); taskInfo.setEndTime(CommonUtils.formatDateTime()); asyncTaskRepository.save(taskInfo); taskTypeFactory.getTaskType(taskId, taskType); }) .exceptionally(e -> { // 更新任务状态为失败 taskInfo.setTaskStatus(StatusEnum.STATUS_FAIL); taskInfo.setEndTime(CommonUtils.formatDateTime()); taskInfo.setFailureReason(e.getMessage()); log.error("Error executing task: {}", e.getLocalizedMessage()); asyncTaskRepository.save(taskInfo); taskTypeFactory.getTaskType(taskId, taskType); return null; });参考此方法,创建一个终止运行中任务的方法
时间: 2024-02-14 13:28:03 浏览: 28
你可以使用`CompletableFuture`的`cancel`方法来取消正在运行的任务。首先,你需要获取到对应任务的`CompletableFuture`对象,然后调用`cancel`方法来取消任务的执行。以下是一个示例方法:
```java
public void cancelTask(String taskId) {
CompletableFuture<?> future = taskFutures.get(taskId);
if (future != null) {
boolean cancelled = future.cancel(true);
if (cancelled) {
// 取消成功,更新任务状态为取消
TaskInfo taskInfo = asyncTaskRepository.findById(taskId);
taskInfo.setTaskStatus(StatusEnum.STATUS_CANCELLED);
taskInfo.setEndTime(CommonUtils.formatDateTime());
asyncTaskRepository.save(taskInfo);
} else {
// 取消失败,可能任务已经完成或已经被取消
// 根据需要进行处理
}
}
}
```
在该方法中,首先通过任务ID从`taskFutures`中获取到对应的`CompletableFuture`对象。然后调用`cancel`方法来取消任务的执行。如果取消成功,你可以根据需求更新任务的状态为取消,并保存到数据库中。如果取消失败,可能是任务已经完成或已经被取消,你可以根据需要进行处理。