Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop execution after a certain time in Java?

Tags:

java

time

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    } 
like image 366
s2000coder Avatar asked Nov 23 '10 02:11

s2000coder


People also ask

How do I stop a Java execution?

To stop executing java code just use this command: System. exit(1);

How do you set a time limit in Java?

To set the time limit of a search, pass the number of milliseconds to SearchControls. setTimeLimit(). The following example sets the time limit to 1 second. // Set the search controls to limit the time to 1 second (1000 ms) SearchControls ctls = new SearchControls(); ctls.

How can we pause the execution of a thread for specific time?

Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.

How do you keep a delay in Java?

The easiest way to delay a java program is by using Thread. sleep() method. The sleep() method is present in the Thread class. It simply pauses the current thread to sleep for a specific time.


1 Answers

long start = System.currentTimeMillis(); long end = start + 60*1000; // 60 seconds * 1000 ms/sec while (System.currentTimeMillis() < end) {     // run } 
like image 191
Matt Ball Avatar answered Oct 16 '22 12:10

Matt Ball