How do I make a delay in Java? How do I make a delay in Java? java java

How do I make a delay in Java?


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();}


Use this:

public static void wait(int ms){    try    {        Thread.sleep(ms);    }    catch(InterruptedException ex)    {        Thread.currentThread().interrupt();    }}

and, then you can call this method anywhere like:

wait(1000);