To add a delay of a few seconds in your Java Program, you can make use of the Thread.sleep() method.
Example:
package org.code2care.examples;
import java.time.LocalDateTime;
public class JavaSleepFewSecondsExample {
public static void main(String[] args) throws InterruptedException {
System.out.println("Sleeping every 2 seconds...");
while(true) {
System.out.println(LocalDateTime.now());
Thread.sleep(2000);
}
}
}
Output:
You can also make use of the java.util.concurrent.TimeUnit class where you can pass in the time duration in seconds unlike milliseconds using Thread class.
Example:package org.code2care.examples;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
public class JavaSleepFewSecondsExample {
public static void main(String[] args) throws InterruptedException {
System.out.println("Sleeping every 2 seconds...");
while(true) {
System.out.println(LocalDateTime.now());
TimeUnit.SECONDS.sleep(2);
}
}
}
Note both these methods thorws InterruptedException which needs to be handled.
References:
Thread.sleep(): https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#sleep(long)
TimeUnit: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/TimeUnit.html
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!