Tuesday, August 7, 2012

Quartz Tutorial : Configure Quartz in web Application

This Tutorial will guide you how to configure Quartz Scheduler in J2EE web Application.
To introduce quartz into the web application we need to specify a context listener into the web application which notify the event of context start up as well as shut down to start and stop the quartz scheduler.
Look in the fallowing example to plug qartz in to the web appliction

Step 1: Create the dynamic web application into the eclipse
Step 2: add the fallowing entries inside web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>TestQuartzApi</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.test.QuartzInitializerListener</listener-class>
</listener>
</web-app>

Step 3: Create your Job which implements Quartz's Job as fallows

package com.test;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job {

@Override
public void execute(JobExecutionContext ctx) throws JobExecutionException {
System.out.println("Quartz is executing my Job");
}

}

Step4 : Create your QuartzInitializerListener class which implements ServletContextListner and override the contextInitialized method,in the contextInitialized method we are providing the configuration regarding Scheduler and Trigger as fallows

package com.test;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzInitializerListener implements ServletContextListener {

public void contextDestroyed(ServletContextEvent arg0){}



public void contextInitialized(ServletContextEvent arg0)
{


System.out.println("Starting The Application");
try{
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();

long ctime = System.currentTimeMillis();

JobDetail job = new JobDetail();
job.setName("MyJobName");
job.setJobClass(MyJob.class);

CronTrigger crt = new CronTrigger();
crt.setName("MyTriggerName");
crt.setCronExpression("0/30 * * * * ?");

scheduler.start();
scheduler.scheduleJob(job, crt);

}catch (Exception e) {
System.out.println(e);
}

}
}

Step 5: Make sure to include quartz api related jar in the build path and run your application,here you goes




No comments: