5-Minutes Tutorial: Integrating Quartz in a J2EE application

This tutorial will show you how to integrate Quartz scheduling in your J2EE applications. Usually, we want to schedule a process as soon as the application server restarts. In this example, we will schedule a SimpleTrigger project that fires every 10 seconds. You should use CronTrigger when you need some more complex schedule (for example, run this thread every Sunday at 5pm). This is as equally easy to use as SimpleTrigger (once you learn the scheduling syntax).

1) Download Quartz from OpenSymphony’s website.

2) Extract quartz-all-1.6.0.jar and jta.jar from the zip file you just downloaded, and put it in your applications WEB-INF/lib directory.

3) Create a new package and create a new Java class. This class is a really simple Quartz Job (it prints “Hello World!”). Here is the code:

package com.startup;
import org.quartz.*;

public class SimpleQuartzJob implements Job{
   
    /** Creates a new instance of SimpleQuartzJob */
    public SimpleQuartzJob() {
    }
    //execute() method must be implemented
    public void execute(JobExecutionContext context) throws JobExecutionException {
  
       System.out.println(”Hellooooo World!”);
}
   
}

4) Create an Application Startup Listener (this class can execute an action whenever you start  or stop your application server). This class will do all work to create, schedule and start a Quartz Scheduler. Please observe the code, and try to play with it once you have this example running:

package com.startup;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.quartz.JobDetail;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import java.util.Date;

public class ApplicationStartup implements ServletContextListener
{
   /**
 * @see javax.servlet.ServletContextListener#void (javax.servlet.ServletContextEvent)
 */
 public void contextDestroyed(ServletContextEvent arg0)
 {
  System.out.println(”THE APPLICATION STOPPED”);
 }

 /**
 * @see javax.servlet.ServletContextListener#void (javax.servlet.ServletContextEvent)
 */
 public void contextInitialized(ServletContextEvent arg0)
 {
  
           
            System.out.println(”THE APPLICATION STARTED”);
            try{
             // Initiate a Schedule Factory
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        // Retrieve a scheduler from schedule factory
        Scheduler scheduler = schedulerFactory.getScheduler();
       
        // current time
        long ctime = System.currentTimeMillis();
       
        // Initiate JobDetail with job name, job group, and executable job class
        JobDetail jobDetail =
         new JobDetail(”jobDetail-s1″, “jobDetailGroup-s1″, SimpleQuartzJob.class);
        // Initiate SimpleTrigger with its name and group name
        SimpleTrigger simpleTrigger =
         new SimpleTrigger(”simpleTrigger”, “triggerGroup-s1″);
        // set its start up time
        simpleTrigger.setStartTime(new Date());
        // set the interval, how often the job should run (10 seconds here)
        simpleTrigger.setRepeatInterval(10000);
        // set the number of execution of this job, set to 10 times.
        // It will run 10 time and exhaust.
        simpleTrigger.setRepeatCount(100);
        // set the ending time of this job.
        // We set it for 60 seconds from its startup time here
        // Even if we set its repeat count to 10,
        // this will stop its process after 6 repeats as it gets it endtime by then.
        //simpleTrigger.setEndTime(new Date(ctime + 60000L));
        // set priority of trigger. If not set, the default is 5
        //simpleTrigger.setPriority(10);
        // schedule a job with JobDetail and Trigger
        scheduler.scheduleJob(jobDetail, simpleTrigger);
       
        // start the scheduler
        scheduler.start();

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

5) Change the web.xml file to add this listener to your application:

<listener>
      <listener-class>com.startup.ApplicationStartup</listener-class>
</listener>

6) Done! Start your application server, and you should see text: “Hello World!” in your console/log file being printed out every 10 seconds. Let it run for a minute or so, and after you stop the app server, you will see the output similar to this:

THE APPLICATION STARTED
Hellooooo World!
Hellooooo World!
Hellooooo World!
Hellooooo World!
Hellooooo World!
Hellooooo World!
THE APPLICATION STOPPED

 Here’s another great Quartz tutorial from IBM: http://www-128.ibm.com/developerworks/library/j-quartz/index.html

About these ads
This entry was published on December 8, 2008 at 7:33 am and is filed under Java/J2EE, Tutorials. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

7 thoughts on “5-Minutes Tutorial: Integrating Quartz in a J2EE application

  1. Mohamed Haneef on said:

    That looks great and simple…

  2. Kevin on said:

    How do i manually stop the Quartz scheduler?

  3. Andrej Sobkowski on said:

    Excellent mini-tutorial! Exactly what I needed and it works perfectly. Thanks a lot.

  4. Frédéric ABRIOUX on said:

    yes, that’s look very simple !

    Very good to understand quickly what it’s possible !

    Thanks.

  5. irfaan on said:

    hi,
    i tried this code. it is not running.

  6. Julian Osorio Amaya on said:

    It works!!!

    Thank you all.

  7. Remi on said:

    The tutorial was simpl great! Looking forward to more such examples.

    I have an issue though. I get a java.lang.NoClassDefFoundError when I try to instantiate any class from within contextInitialized. What am I missing here?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: