I have a while loop and I want it to exit after some time has elapsed.
For example:
while(condition and 10 sec has not passed){
}
Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.
Breaking Out of While Loops. To break out of a while loop, you can use the endloop, continue, resume, or return statement.
Break Statement in C/C++ The break in C or C++ is a loop control statement which is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stops there and control returns from the loop immediately to the first statement after the loop.
An infinite loop is a loop that runs indefinitely and it only stops with external intervention or when a break statement is found. You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.
long startTime = System.currentTimeMillis(); //fetch starting time
while(false||(System.currentTimeMillis()-startTime)<10000)
{
// do something
}
Thus the statement
(System.currentTimeMillis()-startTime)<10000
Checks if it has been 10 seconds or 10,000 milliseconds since the loop started.
EDIT
As @Julien pointed out, this may fail if your code block inside the while loop takes a lot of time.Thus using ExecutorService would be a good option.
First we would have to implement Runnable
class MyTask implements Runnable
{
public void run() {
// add your code here
}
}
Then we can use ExecutorService like this,
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new MyTask()), 10, TimeUnit.SECONDS); // Timeout of 10 seconds.
executor.shutdown();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With