s2000coder s2000coder - 14 days ago 5
Java Question

How to stop execution after a certain time in Java?

In the code, the variable timer would specify the duration after which to end the while loop, 60 sec for example.

while(timer) {
//run
//terminate after 60 sec
}

Answer
long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
    // run
}