# How to pause the code execution in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Oct 1, 2021. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-pause-sleep-delay-wait

> A quick guide to learn how to pause or delay the code execution for a specific amount of time in Java.

Sometimes you want to pause the execution of your Java code for a fixed number of milliseconds or seconds until another task is finished. There are multiple ways to achieve this.

## `Thread.sleep()` method

The quickest way to stop the code execution in Java is to instruct the current thread to sleep for a certain amount of time. This is done by calling the `Thread.sleep()` static method:

```java
try {
    System.out.printf("Start Time: %s\n", LocalTime.now());
    Thread.sleep(2 * 1000); // Wait for 2 seconds
    System.out.printf("End Time: %s\n", LocalTime.now());
} catch (InterruptedException e) {
    e.printStackTrace();
}
```

The code above stops the execution of the current thread for 2 seconds (or 2,000 milliseconds) using the `Thread.sleep()` method. 

Also, notice the `try...catch` block to handle `InterruptedException`. It is used to catch the exception when another thread interrupts the sleeping thread.

This exception handling is necessary for a multi-threaded environment where multiple threads are running in parallel to perform different tasks.

## `TimeUnit.SECONDS.sleep()` method

For better readability, you can also use the `TimeUnit.SECONDS.sleep()` method to pause a Java program for a specific number of seconds as shown below:

```java
try {
    System.out.printf("Start Time: %s\n", LocalTime.now());
    TimeUnit.SECONDS.sleep(2);  // Wait 2 seconds
    System.out.printf("End Time: %s\n", LocalTime.now());
} catch (InterruptedException e) {
    e.printStackTrace();
}
```

Under the hood, the `TimeUnit.SECONDS.sleep()` method also calls the `Thread.sleep()` method. The only difference is readability that makes the code easier to understand for unclear durations.

The `TimeUnit` is not just limited to seconds. It also provides methods for other time units such as nanoseconds, microseconds, milliseconds, minutes, hours, and days:

```java
// Wait 500 nanoseconds
TimeUnit.NANOSECONDS.sleep(500);

// Wait 5000 microseconds
TimeUnit.MICROSECONDS.sleep(5000);

// Wait 500 milliseconds
TimeUnit.MILLISECONDS.sleep(500);

// Wait 5 minutes
TimeUnit.MINUTES.sleep(5);

// Wait 2 hours
TimeUnit.HOURS.sleep(2);

// Wait 1 day
TimeUnit.DAYS.sleep(1);
```

## `ScheduledExecutorService` interface

The sleep times are inaccurate with `Thread.sleep()` when you use smaller time increments like nanoseconds, microseconds, or milliseconds. This is especially true when used inside a loop.

For every iteration of the loop, the sleep time will drift slightly due to other code execution and become completely imprecise after some iterations.

For more robust and precise code execution delays, you should use the `ScheduledExecutorService` interface instead. This interface can schedule commands to run after a given delay or at a fixed time interval.

For example, to run the `timer()` method after a fixed delay, you use the `schedule()` method:

```java
public class Runner {

    public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        // Execute timer after 2 seconds
        service.schedule(Runner::timer, 2, TimeUnit.SECONDS);
    }

    public static void timer() {
        System.out.println("Current time: " + LocalTime.now());
    }
}
```

Similarly, to call the method `timer()` every second, you should use the `scheduleAtFixedRate()` method as shown below:

```java
public class Runner {

    public static void main(String[] args) {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

        // Execute timer every second
        service.scheduleAtFixedRate(Runner::timer, 0, 1, TimeUnit.SECONDS);
    }

    public static void timer() {
        System.out.println("Current time: " + LocalTime.now());
    }
}
``` 

Here is a an example output of the above code:

```bash
Current time: 08:48:11.350034
Current time: 08:48:12.335319
Current time: 08:48:13.337250
Current time: 08:48:14.334107
Current time: 08:48:15.338532
Current time: 08:48:16.336175
...
```
