Java Foreach Loop with Timer for Delayed Iteration
Here is an example of how you can use a 'foreach' loop and a Timer to implement a delay of 1 second every 10 iterations:
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
List<InstList> instLists = instListMapper.selectInstListList(list);
int size = instLists.size();
// Define the number of iterations before the delay
int iterationsBeforeDelay = 10;
for (int i = 0; i < size; i++) {
// Perform the desired actions for each iteration
// Check if it's time for a delay
if ((i + 1) % iterationsBeforeDelay == 0) {
// Create a Timer object
Timer timer = new Timer();
// Schedule a TimerTask to be executed after 1 second
timer.schedule(new TimerTask() {
@Override
public void run() {
// Actions to be performed after the delay
}
}, 1000); // 1000 milliseconds = 1 second
// Wait for the TimerTask to complete
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Cancel the timer
timer.cancel();
}
}
In this example, the 'instLists' list contains 119 elements. The loop iterates through each element, and after every 10 iterations, it creates a Timer object to introduce a delay of 1 second. After the delay, you can perform any desired actions.
原文地址: https://www.cveoy.top/t/topic/bdVb 著作权归作者所有。请勿转载和采集!