Quartz 2 Scheduler example

Quartz is an open source job scheduling framework. It can be used to manage and schedule jobs in the application.

STEP 1 : CREATE MAVEN PROJECT

A maven project is created as below. (It can be created by using Maven or IDE Plug-in).

STEP 2 : LIBRARIES

Quartz dependencies are added to Maven’ s pom.xml. These dependency libraries will be downloaded by Maven Central Repository.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>OTV_Quartz</groupId>
 <artifactId>OTV_Quartz</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <dependencies>

  <!-- Quartz library -->
  <dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz</artifactId>
      <version>2.0.2</version>
  </dependency>   

  <!-- Log4j library -->
  <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.16</version>
  </dependency> 

 </dependencies>

</project>

STEP 3 : CREATE NEW JOB

A new Job is created by implementing the Quartz Job interface as below. TestJob Class specifies business logic which will be scheduled.

package com.otv.job;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class TestJob implements Job {

   private Logger log = Logger.getLogger(TestJob.class);

   public void execute(JobExecutionContext jExeCtx) throws JobExecutionException {
      log.debug("TestJob run successfully...");
   }

}

STEP 4 : LINK JOB WITH JOBDETAIL OBJECT

Created TestJob class is linked with a JobDetail object.

JobDetail job = JobBuilder.newJob(TestJob.class)
       .withIdentity("testJob")
       .build();

STEP 5 : CREATE NEW TRIGGER

A new trigger is created as below. Trigger Class specifies running period of the job which will be scheduled. There are two kind of Quartz Triggers as :

Trigger : specifies start time, end time, running period of the job.

CronTrigger : specifies start time, end time, running period of the job according to Unix cron expression.

//Trigger the job to run on the next round minute
Trigger trigger = TriggerBuilder.newTrigger()
        .withSchedule(
                     SimpleScheduleBuilder.simpleSchedule()
                     .withIntervalInSeconds(30)
                     .repeatForever())
                                   .build();

// CronTrigger the job to run on the every 20 seconds
CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                             .withIdentity("crontrigger","crontriggergroup1")
                             .withSchedule(CronScheduleBuilder.cronSchedule("10 * * * * ?"))
                             .build();

STEP 6 : CREATE SchedulerFactory

A new SchedulerFactory is created and a Scheduler object is gotten from SchedulerFactory Class.

SchedulerFactory schFactory = new StdSchedulerFactory();
Scheduler sch = schFactory.getScheduler();

STEP 7 : START Scheduler

Scheduler Object is started.

// Start the schedule
sch.start();

STEP 8 : SCHEDULE JOB

TestJob is scheduled:

// Tell quartz to schedule the job using the trigger
sch.scheduleJob(job, trigger);

STEP 9 : FULL EXAMPLE

TestJob will run two times per minute.

package com.otv;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.otv.job.TestJob;

/**
* @author onlinetechvision.com
* @since 17 Sept 2011
* @version 1.0.0
*
*/
public class JobScheduler {

   public static void main(String[] args) {

      try {

         // specify the job' s details..
         JobDetail job = JobBuilder.newJob(TestJob.class)
                                   .withIdentity("testJob")
                                   .build();

         // specify the running period of the job
         Trigger trigger = TriggerBuilder.newTrigger()
                                         .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                                                                            .withIntervalInSeconds(30)
                                                                            .repeatForever())
                                          .build();

         //schedule the job
         SchedulerFactory schFactory = new StdSchedulerFactory();
         Scheduler sch = schFactory.getScheduler();
         sch.start();
         sch.scheduleJob(job, trigger);

      } catch (SchedulerException e) {
         e.printStackTrace();
      }
   }

}

STEP 10 : OUTPUT

When JobScheduler Class is run, the output will be seen as below :

17.09.2011 23:39:37 DEBUG (TestJob.java:13) - TestJob run successfully...
17.09.2011 23:40:07 DEBUG (TestJob.java:13) - TestJob run successfully...
17.09.2011 23:40:37 DEBUG (TestJob.java:13) - TestJob run successfully...
17.09.2011 23:41:07 DEBUG (TestJob.java:13) - TestJob run successfully...

STEP 11 : DOWNLOAD
OTV_Quartz_Project

Reference: Quartz 2 Scheduler from our JCG partner Eren Avsarogullari at the Online Technology Vision blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

5 Responses to "Quartz 2 Scheduler example"

  1. tech says:

    Thanks for posting it , very crisp and clear.
    I found some more references on same.

    http://techidiocy.com/quartz-scheduler-framework-in-java-and-integration-with-spring-example/

  2. ice says:

    thx, it is clear and solve me a big problem!!!

  3. Hi,
    Just want to point readers to QuartzDesk (http://www.quartzdesk.com). QuartzDesk is a advanced graphical frontend for the management and monitoring of Quartz schedulers, jobs and triggers running in all sorts of Java applications. Lite (free) license available as well as 30-day trial licenses for all non-free editions. I sincerely hope you will find this new tool useful.

    Best regards,
    Jan Moravec
    QuartzDesk Project Founder

  4. This made my day. Thank you so much.

  5. EU says:

    Thanks for sharing. Just in case anyone encounters ‘log4j:WARN No appenders could be found for logger (org.quartz.impl.StdSchedulerFactory)’ warning, creating a simple log4j.xml and adding this file in your classpath should resolve the warning and you should be able to view the degig message from TestJob class. Details on what needs to go into the log4j.xml file can be found here – http://wiki.apache.org/logging-log4j/Log4jXmlFormat

Leave a Reply


× 9 = twenty seven



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close