This post will discuss how to add a delay in Java for a few seconds.

1. Using ScheduledExecutorService

The idea is to get an executor that can schedule commands to run after a given initial delay or to run periodically. To execute a task once after a delay, use the schedule() method. For example, the following code invokes the run() method after the initial delay of 1 second.

Download Code

Output:

Running

 
To schedule a task to execute periodically, use the scheduleAtFixedRate() method. For example, the following code invokes the run() method every 1 second.

Download Code

Output:

Running
Running


 
You can also use the scheduleWithFixedDelay() method. Here’s an equivalent version that works with Java 7 and less:

Download Code

Output:

Running
Running


2. Using sleep() method

A common solution to temporarily cease execution of the current thread is using the Thread.sleep(ms) method. It causes the thread to sleep for the specified number of milliseconds.

Download  Run Code

Output:

Start…
1 second elapsed…

 
Alternatively, you can use the convenience method unit.sleep(sleepFor) that converts time arguments into the form required by the Thread.sleep() method.

Download  Run Code

Output:

Start…
1 second elapsed…

3. Using Guava

Note that the sleep() method throws an InterruptedException if the thread is interrupted while sleeping. To invoke unit.sleep(sleepFor) uninterruptibly, consider using the Uninterruptibles.sleepUninterruptibly() method offered by Guava.

Download Code

Output:

Start…
1 second elapsed…

That’s all about adding a delay in Java for a few seconds.