Create Schedulers in Java

At a particular point of time every developer needs to run some task background.  In java we have background clean up program nothing but Garbage Collection.

Every developer can achieve these background tasks by using java threads concepts.

They are as follows,
  1. using Simple Thread
  2. using ScheduledExecutorService
  3. using timer task

Using Simple Thread :

This simple thread is very easy to implement. Create a thread and put it in a while loop to execute forever. This will run the thread forever at back end. Provide thread methods to provide interval for running.

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



Using ScheduledExecutorService:



This ScheduledExecutorService is provided in Java 5. 

No comments:

Post a Comment