Scheduling a java program

Scheduling a java program via timer

/*** for one time scheduling*****/

package com.test.demo;


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

/**
 * Simple demo that uses java.util.Timer to schedule a task to execute once 2
 * seconds have passed.
 */

public class OnetimeScheduler {

  Timer timer;

  public OnetimeScheduler(int seconds) {
   
    timer = new Timer();
    timer.schedule(new RemindTask(), seconds * 1000);
  }

  class RemindTask extends TimerTask {
    public void run() {
      System.out.println("Time's up!");
      System.out.println("Hi");
      timer.cancel(); //Not necessary because we call System.exit
      //System.exit(0); //Stops everything
    }
  }

  public static void main(String args[]) {
    System.out.println("About to schedule task.");
    new OnetimeScheduler(2);
    System.out.println("Task scheduled.");
  }
}



/**** for scheduling after every few seconds or mili seconds****/



package com.test.demo;

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

/**
 * Schedule a task that executes once every second.
 */

public class MyScheduler {

  Timer timer;

  public MyScheduler() {
    timer = new Timer();
    timer.schedule(new RemindTask(), 0, //initial delay
        2 * 1000); //subsequent rate
  }

  class RemindTask extends TimerTask {
    //int noOfTimes  = 9;

    public void run() {
     if (noOfTimes > 0) {
        System.out.println("Beep!");
        noOfTimes--;
      } else {
        System.out.println("Time's up!");
        timer.cancel(); //Not necessary because we call System.exit
       // System.exit(0); //Stops everything 
      }
    }
  }

  public static void main(String args[]) {
    System.out.println("About to schedule task.");
    new MyScheduler();
    System.out.println("Task scheduled.");
  }
}








Comments

Popular posts from this blog

Conversion from Clob To String in java and Vice versa

Portable Java 8/ JDK8 setup without admin rights

Multi Threading , Producer consumer problem in Java