Tuesday, May 15, 2007

Have a cronjob in a application server?

Objective: The goal is to run a particualr task at regular interval. Ex: We have emails which are stored in a queue and this needs to be sent to all the recipients. There are several options which can be used to solve this problem -
a) Open source frameworks - Jcrontab. We setup the pattern of time when we would like a given task to be executed. (Pre Java 1.3 time)
b) TimerEJB : http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Session5.html
c) TimerTask & Timer (Part of JDK)

With latest JDK's we can use TimerTask and Timer option as the most simple solution.

Sample Timer:

import java.util.Timer;
import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

public class EMailService extends Timer

private static boolean invokedOnce = false;
private static final Log log = LogFactory.getLog(EMailService.class);
private EMailService() {
public static synchronized void initialize(long delay, long period) {

if (!invokedOnce) {
invokedOnce = true;
EMailService mailService = new EMailService();
mailService.schedule(new SendEmail(), delay, period);
log.info("Timed EMailService has been initialized with delay: " + delay + "(ms) period: " + period + "(ms)");

Sample TimerTask: SendMail:

public class SendEmail extends TimerTask {

private static final Log log = LogFactory.getLog(SendEmail.class);


public void run()
long threadId = Thread.currentThread().getId();

How Timer Classes are initializd?

Typically this can be invoked from a Servlet which can be called during startup.

No comments: