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.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

2 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!!!

Leave a Reply


− 3 = three



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
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.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books