Java – How to delay few seconds
In Java, we can use TimeUnit.SECONDS.sleep()
or Thread.sleep()
to delay few seconds.
1. TimeUnit
JavaDelayExample.java
package com.mkyong;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class JavaDelayExample {
public static void main(String[] args) {
try {
System.out.println("Start..." + new Date());
// delay 5 seconds
TimeUnit.SECONDS.sleep(5);
System.out.println("End..." + new Date());
// delay 0.5 second
//TimeUnit.MICROSECONDS.sleep(500);
// delay 1 minute
//TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
System.err.format("IOException: %s%n", e);
}
}
}
output
Start...Mon Apr 08 21:42:55 SRET 2019
End...Mon Apr 08 21:43:00 SRET 2019
2. Thread.sleep
JavaDelayExample2.java
package com.mkyong;
import java.util.Date;
public class JavaDelayExample2 {
public static void main(String[] args) {
try {
System.out.println("Start..." + new Date());
// delay 5 seconds
Thread.sleep(5000);
System.out.println("End..." + new Date());
} catch (InterruptedException e) {
System.err.format("IOException: %s%n", e);
}
}
}
This was helpful, thank you very much. But (I say this mostly as a sanity-check on myself not to correct you, pls pls tell me if I’m wrong), in example 1), “TimeUnit.MICROSECONDS.sleep(500)” stalls for 0.0005 seconds, not 0.5s; that’s “MILLISECONDS”.
stop
How about:
TimeUnit.SECONDS.sleep(5);
It’s essentially the same but is nicer to read. (My opinion)
Article is updated with TimeUnit, thanks ~
I am in this discussoio0n
Thanks sir, This help me a lot to resolve my issue.
how to delay many seconds ? ))
5 sec