[java] How to make java delay for a few seconds?

Hey all I have this code. I want to delay my program for a few seconds and display "scanning..."

Here's what I have. This compiles but doesn't delay anything

 if (i==1){

        try {
            Thread.sleep(1);
        } catch (InterruptedException ie)
        {
            System.out.println("Scanning...");
        }

    }

thanks in advance I have int i = 1 before obviously

This question is related to java delay

The answer is


This is in a mouseEvent btw

If this is in a Swing GUI, then get rid of all calls to Thread.sleep(...) as doing so can put the entire GUI to sleep rendering it useless. Instead use a Swing Timer to produce any delays in the GUI while letting it still update its graphics.

You'll also want to avoid System.out.println(...) calls, except when debugging, and instead display user notifications in the GUI itself, perhaps in a status JLabel or as a message dialog.


Thread.sleep() takes in the number of milliseconds to sleep, not seconds.

Sleeping for one millisecond is not noticeable. Try Thread.sleep(1000) to sleep for one second.


Use Thread.sleep(2000); //2000 for 2 seconds


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

This is used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can’t be negative, else it throws IllegalArgumentException.

FYI (Summary taken from here)

Java Thread Sleep important points

  • It always pause the current thread execution.
  • Thread sleep doesn’t lose any monitors or locks current thread has acquired.
  • Any other thread can interrupt the current thread in sleep, in that case InterruptedException is thrown.

move the System.out statement to finally block.


A couple problems, you aren't delaying by much (.sleep is milliseconds, not seconds), and you're attempting to print in your catch statement. Your code should look more like:

if (i==1) {
    try {
        System.out.println("Scanning...");
        Thread.sleep(1000); // 1 second
    } catch (InterruptedException ex) {
        // handle error
    }
}

waiting for some(like 10) seconds your compiler to use this static class method
TimeUnit.SECONDS.sleep(10);
it's including in java.util.concurrent.TimeUnit libery


As per java documentation definition of Thread.sleep is :

Thread.sleep(t);
where t => time in millisecons to sleep

If you want to sleep for 1 second you should have :

Thread.sleep(1000);

Java:

For calculating times we use this method:

import java.text.SimpleDateFormat;
import java.util.Calendar;


    public static String getCurrentTime() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    return sdf.format(cal.getTime());
}

Second:

import java.util.concurrent.TimeUnit;

System.out.println("Start delay of 10 seconds, Time is: " + getCurrentTime());
TimeUnit.SECONDS.sleep(10);
System.out.println("And delay of 10 seconds, Time is: " + getCurrentTime());

Output:

Start delay of 10 seconds, Time is: 14:19:08

And delay of 10 seconds, Time is: 14:19:18

Minutes:

import java.util.concurrent.TimeUnit;

System.out.println("Start delay of 1 Minute, Time is: " + getCurrentTime());
TimeUnit.MINUTES.sleep(1);
System.out.println("And delay of 1 Minute, Time is: " + getCurrentTime());

Output:

Start delay of 1 Minute, Time is: 14:21:20

And delay of 1 Minute, Time is: 14:22:20

Milliseconds:

import java.util.concurrent.TimeUnit;

System.out.println("Start delay of 2000 milliseconds, Time is: " +getCurrentTime());
TimeUnit.MILLISECONDS.sleep(2000);
System.out.println("And delay of 2000 milliseconds, Time is: " + getCurrentTime());

Output:

Start delay of 2000 milliseconds, Time is: 14:23:44

And delay of 2000 milliseconds, Time is: 14:23:46

Or:

Thread.sleep(1000); //milliseconds

If you want to pause then use java.util.concurrent.TimeUnit:

TimeUnit.SECONDS.sleep(1);

To sleep for one second or for 10 minutes

TimeUnit.MINUTES.sleep(10);

Or Thread Sleep

try        
{
    Thread.sleep(1000);
} 
catch(InterruptedException ex) 
{
    Thread.currentThread().interrupt();
}

see also the official documentation

TimeUnit.SECONDS.sleep() will call Thread.sleep. The only difference is readability and using TimeUnit is probably easier to understand for non obvious durations.

but if you want to solve your issue

        int timeToWait = 10; //second
        System.out.print("Scanning")
        try {
            for (int i=0; i<timeToWait ; i++) {
                Thread.sleep(1000);
                System.out.print(".")
            }
        } catch (InterruptedException ie)
        {
            Thread.currentThread().interrupt();
        }

 new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    if (getActivity() != null)
                        getActivity().runOnUiThread(() -> tvCovidAlert.startAnimation(animBounce));
                }
            }, DELAY_TIME_MILI_SECONDS);

You have System.out.println("Scanning...") in a catch block. Do you want to put that in try?