Delay Code Execution in Java

Posted By : Keshav Agarawal | 07-Aug-2019

When a Java program runs on the machine, this process contains at least one thread – the main thread – in which the program runs.
Let see how can we apply delay or pause:-

1. By using the Thread class sleep method:

A simple way to pause in Java is to tell the current thread to sleep for a specific amount of time. This can be done by calling Thread.sleep(milliseconds) method as follows:

try {
  Thread.sleep(secondsToSleep * 1000);
} catch (InterruptedException ex) {
  ex.printStackTrace();
}

It's a good practice to wrap the sleep method in a try/catch block in case another thread interrupts the sleeping thread. 

2. By using the TimeUnit class:

We can use the TimeUnit.SECONDS.sleep(100), where SECONDS is the time unit to sleep for 100 seconds.

We can use the TimeUnit.MINUTES.sleep(5), where MINUTES is the time unit to sleep for 5 minutes.

We can use the TimeUnit.HOURS.sleep(2), where HOURS is the time unit to sleep for 2 hours.

We can use the TimeUnit.DAYS.sleep(3), where DAYS is the time unit to sleep for 3 days.

Here’s an example of the TimeUnit syntax:

try {
  TimeUnit.SECONDS.sleep(secondsToSleep);
} catch (InterruptedException ie) {
  ex.printStackTrace();
}

The Disadvantage of using sleep() method:
      Yes, there is a disadvantage of using sleep() method, i.e. if you use sleep() method inside a loop or over iteration, for each iteration, the code execution will be delayed. So overall delay time will be increased.

3. By using Timer and TimerTask class:

Here are some steps that can be followed.

1. Create a SchedulerTask class as the subclass of the TimerTask

2. The code that performs the task should be placed in the run() method.

3. Create a thread by instantiating the Timer class. 

4. Instantiate the timer task object (new SchedulerTask()). 

5. This example uses the schedule method, with the timer task as the first argument i.e. an instance of SchedulerTask. And the second argument is the delay in milliseconds i.e. 5000L.

6. Pass these both arguments inside Timer class method i.e. scheduleAtFixedRate();

7. Now just invoke the startScheduler() method.

public class Test{
  void startScheduler() {
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new SchedulerTask(), 5000L); 
  }
}
public class SchedulerTask extends TimerTask {
  @Override
  public void run() {
    try {
     // code that need to be executed after this delay
    }
    catch (Exception ex) {
     ex.printStackTrace();
    }
  }
}

This run() method will be invoked automatically as the 5000 milliseconds completed and the code placed inside the run() method will be executed.

4. By Using ScheduledExecutorService class:


Here are some steps that can be followed:

1. Define a method that will be executed after the delay.

public void executeMyTask(){
  System.out.println("Task executed");
}

2. Create a class that implements the Runnable interface.
3. Override run() method and call the method that you want to execute after the delay.

class Test implements Runnable{
  @Override
  public void run() {
    executeMyTask();
  }
}

4. Now, create an instance of a ScheduledExecutorService class by calling newSingleThreadScheduledExecutor() method of Executors class, which is a static method.
5. Call the schedule() method of ScheduledExecutorService class by passing the following argument.
    The first argument will be the instance of an implementing class of Runnable interface.
    The second argument will be the time to delay the execution.
    The third argument will be the time unit of delay i.e SECONDS or MINUTES, etc.

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Test(), 5, TimeUnit.SECONDS);

About Author

Author Image
Keshav Agarawal

Keshav Agarawal is Java Developer with skilled in Java, Servlet, JSP, JDBC, Spring Boot, Spring MVC, JPA, Hibernate. His hobbies are playing chess and reading books in free time. By nature he is friendly and honest person.

Request for Proposal

Name is required

Comment is required

Sending message..