Java TimerTask provides a way to schedule a task using the standard Java Timer class. This is quite handy when we want to run a task at regular time intervals. Another practical application of this feature is to perform a hard timeout on HTTP calls when the user experience is suffering due to long running HTTP calls.

We will be seeing both the use-cases in this post with code examples.

1 – Introduction to Java TimerTask

Java TimerTask is an in-built class that implements the Runnable interface. We need to extend this class to create our own TimerTask that can be scheduled using the Java Timer class.

Java Timer class is thread-safe in nature. In other words, multiple threads can share a single Timer object without any need for external synchronization.

See below example code to understand Java TimerTask.

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimeTaskDemo extends TimerTask {

    @Override
    public void run() {
        System.out.println("Starting Timer Task at:" + new Date());
        executeTask();
        System.out.println("Finishing Timer Task at:" + new Date());
    }

    private void executeTask() {
        try {
            //assuming it takes 5 secs to complete the task
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TimerTask timerTask = new TimeTaskDemo();

        Timer timer = new Timer(true);
        timer.scheduleAtFixedRate(timerTask, 0, 10*1000);
        System.out.println("Timer Task Started");

        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        timer.cancel();
        System.out.println("Timer Task Cancelled");

        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Let us try to understand what is going on here:

  • The TimerTaskDemo class extends the abstract TimerTask class and overrides the run() method.
  • In the run() method, we simply simulate a task execution by making the thread sleep for 5 seconds.
  • Now, in the main() method, we instantiate the TimerTaskDemo class and also the Timer class. The Timer class constructor takes the flag isDaemon as input. We set it to true.
  • Then, we schedule the timerTask using scheduleAtFixedRate() method provided by the Timer class.
  • The scheduleAtFixedRate() method takes 3 arguments – the TimerTask instance, delay in task execution and interval between successive tasks. Here, delay is 0 seconds and interval is 10 seconds.
  • Lastly, we let the thread sleep for 15 seconds to allow the tasks to be executed. Finally, we cancel the timer using the cancel() method.

If we run the above program, below is the output we will get:

Timer Task Started
Starting Timer Task at:Sat Jul 03 09:13:02 IST 2021
Finishing Timer Task at:Sat Jul 03 09:13:07 IST 2021
Starting Timer Task at:Sat Jul 03 09:13:12 IST 2021
Timer Task Cancelled
Finishing Timer Task at:Sat Jul 03 09:13:17 IST 2021

Process finished with exit code 0

Some important points:

  • If a task is already running, the Timer will wait for it to finish before starting the next task from the queue.
  • We can execute tasks as daemon threads. Daemon threads are basically low priority threads that perform background operations.
  • Cancel method terminates the timer and discards any scheduled tasks. However, running tasks will still finish.
  • If we run the timer as daemon thread, it will terminate as soon as all threads finish execution.

2 – Java TimerTask for HTTP Calls

Now that we have understood the basics of Java TimerTask, we can move to the main objective of this post. The objective is to use Java TimerTask to perform hard timeout for HTTP Calls.

If you are not aware about Java HTTPClient timeout properties, you can go through this post where we talk in detail about the various timeout properties. On a basic level, there are various type of timeouts such as socket timeout, connection timeout. We can set all these properties individually.

However, many times we also need to have an overall hard timeout on the request level. For example, during the download of a potentially large file, the connection may be established but we need to ensure that the operation doesn’t go over a certain threshold. The Java HTTPClient does not have any configuration that can help us achieve such a hard timeout. However, it does provide an abort functionality that we can use along with the TimerTask to achieve hard timeout.

Below is the example code for the same.

HttpGet getMethod = new HttpGet(
  "http://localhost:8080/api/employees/1");

int hardTimeout = 5; // seconds
TimerTask task = new TimerTask() {
    @Override
    public void run() {
        if (getMethod != null) {
            getMethod.abort();
        }
    }
};
new Timer(true).schedule(task, hardTimeout * 1000);

HttpResponse response = httpClient.execute(getMethod);
System.out.println(
  "HTTP Status of response: " + response.getStatusLine().getStatusCode());

As you can see here, we create a HttpGet object. Next, we create a TimerTask and override its run() method to abort the HTTP call whenever required. Now, we can schedule the task to run after 1 second. Basically, we imply that after 1 second, the abort() method will be called and the HTTP call will terminate. Lastly, we execute the getMethod using httpClient.


With this, we complete our demonstration of Java TimerTask and how we can use it to achieve hard timeout for HTTP requests using the abort() method.

Categories: BlogJava

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *