Java job scheduling and cron

January 31st, 2009 | Tags: , , ,

More often than not you need your java program to perform an operation at a particular time. It gets trickier when the operation needs to be performed at regular intervals. There are a lot of solutions to implement a java “cron” of sorts available. There’s the quartz scheduler which has pretty much everything that you will ever need in terms of scheduling, then there’s Spring TaskExecutor’s which can do pretty much everything but are a lot easier to configure than a full blown job scheduler.

However, for a simple task, say executing a simple query on your database, you don’t really need either of the above. Infact they become more of a hindrance than help. One of the most overlooked classes of the JDK is the Timer class. As the docs state, the class can do the job of a cron for you. It executes tasks at a particular time and then even schedules them for re-execution every x seconds. Much better than using a full blown task scheduler.

Simple example :

package com.codercorp.thread;

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

public class TimerTest {

	public static void main(String[] args) {
		Calendar c = Calendar.getInstance();
		c.roll(Calendar.MINUTE, true);
		Timer t = new Timer(false);
		t.schedule(new TimerTasker(), c.getTime(), 1000);
	}

	private static class TimerTasker extends TimerTask {

		@Override
		public void run() {
			System.out.println("Running ...");
		}

	}
}

Thats it, your java cron is ready.

Share and Enjoy:
  • del.icio.us
  • Google Bookmarks
  • DZone
  • Reddit
  • Digg
  • Facebook
  • Netvibes
  • StumbleUpon
  • Technorati
  • LinkedIn
  • MySpace
  • Print
  • Slashdot
  • Share/Bookmark

No related posts.

  1. n002213f
    May 5th, 2009 at 11:48
    Reply | Quote | #1

    many thanks for such a good and useful tip. I concur with you, sometimes quartz and company are a hindrance, all i wanted was a bread not swiss knife.

    • Gaurav Arora
      May 6th, 2009 at 22:50
      Reply | Quote | #2

      Glad to be of help.