How do I make a delay in Java?

1,711,066

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

You need to use the Thread.sleep() call.

More info here: http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

Solution 5

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]);
        }
    }
}
Share:
1,711,066
ardb
Author by

ardb

Updated on December 06, 2021

Comments

  • ardb
    ardb over 2 years

    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 = 0;
        }
    
        ceva[i].setSelected(true);
    
        // I need to wait here
    
        ceva[i].setSelected(false);
    
        // I need to wait here
    
        i++;
    }
    

    I want to build a step sequencer and I'm new to Java. Any suggestions?

  • m0skit0
    m0skit0 over 7 years
    Don't forget to log the InterruptedException or you will never know this thread got interrupted.
  • atlas_scoffed
    atlas_scoffed over 6 years
    @Matthew Moisen I couldn't get this Java 8 example to run. What is App:: exactly? By changing myTask() to a runnable lambda it works: Runnable myTask = () -> {...};
  • Boris the Spider
    Boris the Spider over 6 years
    It's a method reference @comfytoday - I suggest starting with the documentation.
  • John
    John over 6 years
    TimeUnit.SECONDS.wait(1) is throwing IllegalMonitorStateException in Java 8.1 build 31 on Windows 6.3. Instead, I'm able to use Thread.sleep(1000) without a try/catch.
  • Boris the Spider
    Boris the Spider over 6 years
    You called wait not sleep @JohnMeyer. Be more careful.
  • Brent212
    Brent212 over 5 years
    I'm curious as to what the Thread.currentThread().interrupt(); does here.
  • Marco13
    Marco13 over 5 years
    Using catch (InterruptedException e) { /* empty */ } is NOT a sensible solution here. At the very least, you should provide some log information. For more information about the subject, see javaspecialists.eu/archive/Issue056.html
  • Tristan
    Tristan over 5 years
    see : "Why do we have to interrupt the thread again?" here : javaspecialists.eu/archive/Issue056.html
  • Shai Alon
    Shai Alon over 4 years
    In Java 8, in java.util.concurrent.TimeUnit you get Unhandled exception: java.lang.InterruptedExecution for the sleep(1)
  • Shai Alon
    Shai Alon over 4 years
    You must surround the TimeUnit.SECONDS.sleep(1); with try catch
  • Stephane
    Stephane over 4 years
    @ShaiAlon What can one usually have in that catch block ?
  • need_to_know_now
    need_to_know_now about 3 years
    If anyone is still struggling with this function, make the enclosing function that calls sleep() throw InterruptedException with throws and catch it where the function is being called. @Stephane Or simply enclose that statement in a try-catch to catch the InterruptedException and print the stack trace.
  • Michael Gantman
    Michael Gantman almost 3 years
    @Marco13 Actually due to your comment and comments from some other people I modified the method TimeUtils.sleepFor() and now it interrupts current thread. So, it is still convenient in a way that you don't need to catch the InterruptedException, but the interruption mechanism now works.
  • Dirk Schumacher
    Dirk Schumacher almost 3 years
    What does Thread.currentThread().interrupt(); do? Why is it important?
  • Dirk Schumacher
    Dirk Schumacher almost 3 years
    Looking at the almost same answer by @Hecanet there is no Thread.currentThread().interrupt(); If it is important why is it not shown? - If it is not important why would it be inserted/omitted?