Scheduling jobs in Java without using third party APIs (uses Timer and TimerTask classes)

This is a simple tutorial that shows how easily (and without depending on third party APIs) you can write a simple scheduler in Java. Java comes with build in capability for scheduling using java.util.Timer class and java.util.TimerTask class.

package com.kushal.tools;
/**
 * @Author Kushal Paudyal
 * Scheduling a task using Java in-house scheduler
 * Created : 2011/04/28
 * Last Modified: 2011/04/28
 */
import java.util.Timer;
import java.util.TimerTask;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;

public final class SchedulerUsingJavaUtil extends TimerTask {
	private final static long FREQUENCY_ONE_DAY = 1000 * 60 * 60 * 24;

	private final static int ONE_DAY = 0;
	private final static int HOUR_AM = 10;
	private final static int MINUTES = 52;

	/**
	 * Construct and use a TimerTask and Timer.
	 */
	public static void main(String[] arguments) {
		TimerTask scheduledTask = new SchedulerUsingJavaUtil();
		Timer timer = new Timer();
		/**
		 * Schedules the specified task for repeated fixed-rate execution,
		 * beginning at the specified time. Subsequent executions take place at
		 * approximately regular intervals, separated by the specified period.
		 * In fixed-rate execution, each execution is scheduled relative to the
		 * scheduled execution time of the initial execution. If an execution is
		 * delayed for any reason (such as garbage collection or other
		 * background activity), two or more executions will occur in rapid
		 * succession to "catch up." In the long run, the frequency of execution
		 * will be exactly the reciprocal of the specified period (assuming the
		 * system clock underlying Object.wait(long) is accurate).
		 *
		 * Fixed-rate execution is appropriate for recurring activities that are
		 * sensitive to absolute time, such as ringing a chime every hour on the
		 * hour, or running scheduled maintenance every day at a particular
		 * time. It is also appropriate for recurring activities where the total
		 * time to perform a fixed number of executions is important, such as a
		 * countdown timer that ticks once every second for ten seconds.
		 * Finally, fixed-rate execution is appropriate for scheduling multiple
		 * repeating timer tasks that must remain synchronized with respect to
		 * one another.
		 *
		 *
		 * Parameters:
		 * task - task to be scheduled.
		 * firstTime - First time at which task is to be executed.
		 * period - time in milliseconds between successive task executions.
		 * Throws: IllegalArgumentException - if
		 * time.getTime() is negative. IllegalStateException - if task was
		 * already scheduled or cancelled, timer was cancelled, or timer thread
		 * terminated.
		 */
		timer.scheduleAtFixedRate(scheduledTask, getFirstRunTime(),FREQUENCY_ONE_DAY);
	}

	/**
	 * Implements TimerTask's abstract run() method.
	 */
	public void run() {
		System.out.println("Doing some task..."+new Date());
	}

	/**
	 * Create a time when scheduler needs to run first
	 */
	private static Date getFirstRunTime() {
		/**
		 * Get Today's Calendar
		 */
		Calendar tomorrow = new GregorianCalendar();
		/**
		 * Add one day to get tomorrow's calendar
		 */
		tomorrow.add(Calendar.DATE, ONE_DAY);
		/**
		 * Set the scheduled time for tomorrow.
		 */
		Calendar firstRunTime = new GregorianCalendar(
				tomorrow.get(Calendar.YEAR),
				tomorrow.get(Calendar.MONTH),
				tomorrow.get(Calendar.DATE),
				HOUR_AM,
				MINUTES);

		return firstRunTime.getTime();
	}
}

What Makes An Agile Story Good? It’s the INVESTment.

When you are writing the agile stories, what features do you consider to make them good? There is this INVEST principal, which guides you to analyze if your stories are good enough. The acronym INVEST can be expanded to very important features that an agile story needs to have. Although achieving this might not always be possible, it’s the best way that works on most of the cases.

Here is what INVEST means.

  • I – Independent (your stories should stand alone so that it canĀ prioritizedĀ as a next work)
  • N – Negotiable (Stories should be negotiable – should be brief and allow the finer details later)
  • V – Valuable (Story should have value to the customer. Too much technical stuff without business outcome is not a good story)
  • E – Estimable (Story which are good are the ones whose boundaries are clearly defined and can be estimated. Vagueness should be removed.
  • S – Small (Should be small enough to fit into one iteration)
  • T – Testable (There is clear expectation, acceptance criteria so that testers can test it when the work is done).

These are the guiding principals, not the standards.

Java Reflections Tutorial

This tutorial gives an insight on how Java Reflection can be used to load Java classes dynamically at the run time. Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

package com.kushal.utilities;

/**
 * @author Kushal Paudyal
 * 08/05/2008
 * 
 * Simple demonstration of Java Reflection mechanism to
 * instantiate a class, get it's method and call that
 * method with proper parameter passing.
 */
import java.lang.reflect.*;

public class JavaReflectionsDemo {

	public static void main(String args[]) {
		try {
			/*
			 * Step 1 Define a class loader
			 */
			ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
			/*
			 * Step 2: Define a class to be loaded.
			 */
			String classNameToBeLoaded = "com.kushal.utilities.DemoClassToBeLoaded";

			/*
			 * Step 3: Load the class
			 */
			Class myClass = myClassLoader.loadClass(classNameToBeLoaded);

			/*
			 *Step 4: create a new instance of that class
			 */
			Object whatInstance = myClass.newInstance();

			String methodParameter = "ABC";
			/*
			 * Step 5: get the method, with proper parameter signature.
			 * The second parameter is the parameter type.
			 * There can be multiple parameters for the method we are trying to call, 
			 * hence the use of array.
			 */

			Method myMethod = myClass.getMethod("myMethod123",
					new Class[] { String.class });

			/*
			 *Step 6:
			 *Calling the real method. Passing methodParameter as
			 *parameter. You can pass multiple paramters based on 
			 *the signature of the method you are calling. Hence
			 *there is an array. 
			 */
			String returnValue = (String) myMethod.invoke(whatInstance,
					new Object[] { methodParameter });

			System.out.println("The value returned from the method is:"
					+ returnValue);

			/*
			 * Catching Probable Exceptions
			 * You can simply catch the Generic 'Exception' to reduce your coding.		 
			 */
		} catch (ClassNotFoundException e1) {
			System.out.println("EXCEPTION:CLASS NOT FOUND");
		} catch (IllegalAccessException e2) {
			System.out.println("EXCEPTION:ILLEGAL ACCESS");
		} catch (InstantiationException e3) {
			System.out.println("EXCEPTION:INSTANTIATION EXCEPTION");
		} catch (NoSuchMethodException e4) {
			System.out.println("EXCEPTION:NO SUCH METHOD");
		} catch (InvocationTargetException e5) {
			System.out.println("EXCEPTION: INVOCATION TARGET");

		}
	}

}
/**
 * @author Kushal Paudyal
 * 08/05/2008
 * www.sanjaal.com/java
 */

/*
 * This is the demo class that we will use to load and invoke method
 * using Java Reflection.
 */
class DemoClassToBeLoaded {
	public static String myMethod123(String someParam) {
		System.out.println("You Are Calling myMethod()");
		System.out.println("You Passed " + someParam + " as Parameter");

		/*
		 * Just returning the current class name
		 * This is just an example method. 
		 */
		return DemoClassToBeLoaded.class.getName();
	}

}