Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a while loop after a certain time?

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){

}
like image 981
Roland Avatar asked Nov 01 '13 12:11

Roland


People also ask

How do you break a while loop in python after time?

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.

How do I force a while loop to exit?

Breaking Out of While Loops. To break out of a while loop, you can use the endloop, continue, resume, or return statement.

How do you exit a while loop after a certain time C++?

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.

How do I stop a while loop running infinitely?

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.


1 Answers

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();
like image 95
Ankit Rustagi Avatar answered Oct 01 '22 17:10

Ankit Rustagi