I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.
while (true) {
if (i == 3) {
i
I know this is a very old post but this may help someone:
You can create a method, so whenever you need to pause you can type pause(1000)
or any other millisecond value:
public static void pause(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
System.err.format("IOException: %s%n", e);
}
}
This is inserted just above the public static void main(String[] args)
, inside the class. Then, to call on the method, type pause(ms)
but replace ms
with the number of milliseconds to pause. That way, you don't have to insert the entire try-catch statement whenever you want to pause.
You need to use the Thread.sleep()
call.
More info here: http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
If you want to pause then use java.util.concurrent.TimeUnit
:
TimeUnit.SECONDS.sleep(1);
To sleep for one second or
TimeUnit.MINUTES.sleep(1);
To sleep for a minute.
As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep
.
Further, sleep
isn't very flexible when it comes to control.
For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay.
For example, to run the method myTask
every second (Java 8):
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
And in Java 7:
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
myTask();
}
}, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
Use Thread.sleep(1000)
;
1000
is the number of milliseconds that the program will pause.
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
One quick solution I am using is (to wait two seconds):
long startTime = System.currentTimeMillis();
while(System.currentTimeMillis() - startTime < 2000) { }
I referred to this when choosing System.currentTimeMillis() over System.nanoTime(): https://www.geeksforgeeks.org/java-system-nanotime-vs-system-currenttimemillis/
DISCLAIMER: I am relatively new to coding and it is very possible that this is unsafe in some way. I couldn't find anything online against using a loop like this, but I do not want to guarantee this as a safe solution to your problem.
Use Thread.sleep(100);
.
The unit of time is milliseconds
For example:
public class SleepMessages {
public static void main(String args[])
throws InterruptedException {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
for (int i = 0;
i < importantInfo.length;
i++) {
//Pause for 4 seconds
Thread.sleep(4000);
//Print a message
System.out.println(importantInfo[i]);
}
}
}