import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; @Component public class ScheduledTasks { @Scheduled(fixedDelay = 5000) public void performTask() { System.out.println("Task started at: " + System.currentTimeMillis()); List> futures = new ArrayList<>(); // 在for循环中执行异步任务 for (int i = 0; i < 5; i++) { CompletableFuture future = CompletableFuture.runAsync(() -> { try { Thread.sleep(2000); // 假设异步任务需要2秒钟完成 System.out.println("Async task completed at: " + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } }); futures.add(future); } // 等待所有异步任务完成 CompletableFuture allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); allOf.join(); // 所有异步任务完成后,进行下一步操作 System.out.println("All async tasks completed. Proceeding to the next step at: " + System.currentTimeMillis()); } }