Sentry Answers>Java>

How to add a delay in Java

How to add a delay in Java

Venter C.

The Problem

I don’t know how to delay an execution for a specified period of time in Java.

The Solution

You can use either the Thread.sleep() method or the ScheduledExecutorService interface to add an execution delay in Java.

Using Thread.sleep()

You can use Thread.sleep() to delay the execution of a task by putting a thread to sleep for a specified number of milliseconds.

For example, the following adds a three-second execution delay by putting the thread to sleep for 3,000 milliseconds:

Click to Copy
public class Main { public static void main(String[] args) { System.out.println("Task started"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Task completed after 3 seconds delay"); } }

The Thread.sleep() method is simple to implement but may not be suitable for all use cases, as it blocks the current thread and doesn’t offer flexible task control. It is best used in situations that require a simple once-off delay within a single thread.

It is important to wrap the Thread.sleep() method in a try-catch block to handle the InterruptedException that is thrown if the thread is interrupted while sleeping.

Using ScheduledExecutorService

The ScheduledExecutorService interface provides more flexible control, allowing you to schedule delayed or periodically executed tasks.

Similar to the Thread.sleep() example, the following code delays the execution of a task by three seconds:

Click to Copy
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // 1 is the size of the thread pool being created System.out.println("Scheduling a task with a 3-second delay"); scheduler.schedule(() -> { System.out.println("Task executed after 3 seconds"); // Task to be executed after the delay }, 3, TimeUnit.SECONDS); // Adding the 3-second delay scheduler.shutdown(); } }

The task will run after the specified time (3 seconds in this case).

The ScheduledExecutorService interface is slightly more complex to implement, but it doesn’t block the current thread. It’s best used in situations that require more complex scheduling and control.

Further Reading

  • Sentry BlogException Handling in Java (with Real Examples)
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.