About Abhijeet Sutar

Abhijeet (ajduke) is self-taught, self-organized software developer. His current go to language is Java and also he is exploring other languages such as Scala, Ruby.

[Java] How to Schedule a task to run in an interval

There is often need in application to run some particular task in background to accomplish some work in an interval. The example can be, service running in background for cleanup of application just like, we have the Java Garbage collection.

In this article, i will show you 3 different ways to achieve this

They are as follows

  • using simple thread
  • using TimerTask
  • using ScheduledExecutorService

using simple thread

This is very simple, which creates the simple thread puts it run in forever with use of while loop and makes use of sleep method to put the interval between running.

This is simply fast and quick way to achieve it

Following is code for this.

public class Task1 {

public static void main(String[] args) {
  // run in a second
  final long timeInterval = 1000;
  Runnable runnable = new Runnable() {
  
  public void run() {
    while (true) {
      // ------- code for task to run
      System.out.println("Hello !!");
      // ------- ends here
      try {
       Thread.sleep(timeInterval);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      }
    }
  };
  
  Thread thread = new Thread(runnable);
  thread.start();
  }
}

using the Timer and TimerTask

Previous method we saw was very quickest possible, but it lacks some functionality

This has much more benefits than previous they are as follows

  • control over when start and cancel task
  • first execution can be delayed if wanted, provides useful

In this we use, Timer class for scheduling purpose and TimerTask is used for enclosing task to be executed inside its run() method.

Timer instance can be shared to schedule the multiple task and it is thread-safe.

When Timer constructor is called , it creates one thread and this single thread is used any scheduling of task.

For our purpose, we use Timer#scheduleAtFixedRate

Following code shows the use of Timer and TimerTask

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

public class Task2 {

  public static void main(String[] args) {
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        // task to run goes here
        System.out.println("Hello !!!");
      }
    };
    
    Timer timer = new Timer();
    long delay = 0;
    long intevalPeriod = 1 * 1000; 
    
    // schedules the task to be run in an interval 
    timer.scheduleAtFixedRate(task, delay,
                                intevalPeriod);
  
  } // end of main
}

These classes are classes existed from the JDK 1.3.

using ScheduledExecutorService

This is introduced in java.util.concurrent from Java SE 5 as Concurrency utilities. This is preferred way to achieve the goal.

It provides following benefits as compared to previous solutions

  • pool of threads is used to execute as compared TImer`s single thread
  • Provides the flexibility for delaying first execution
  • Provides nice conventions for providing the time intervals

Following code shows use of same,

In this, we use ScheduledExecutorService#scheduleAtFixedRate as shown , it takes param as runnable which particular piece of code we want to run , initialdelay for first execution

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Task3 {

  public static void main(String[] args) {
    
    Runnable runnable = new Runnable() {
      public void run() {
        // task to run goes here
        System.out.println("Hello !!");
      }
    };
    
    ScheduledExecutorService service = Executors
                    .newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
  }
}

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "[Java] How to Schedule a task to run in an interval"

  1. Mohit Sareen says:

    Nice post but it would be more useful if you include the Quartz Api also.

Leave a Reply


+ 7 = twelve



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close