Enterprise Java

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).
 
 
Quartz2

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

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

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

8 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
tech
11 years ago

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/

ice
ice
11 years ago

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

Jan Moravec
10 years ago

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

Juan Sebastián Ocampo Ospina

This made my day. Thank you so much.

EU
10 years ago

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

Jai
Jai
9 years ago

I am getting compilation error.

The method newJob(Class) in the type JobBuilder is not applicable for the arguments (Class).

Any thought?

aparna
aparna
6 years ago
Reply to  Jai

Please download latest jar quartz 2.1.5 from maven repository. now remove all import statements and try ctrl + shift+ o once. it will automatically resolve it.

Raj
Raj
3 years ago
Reply to  aparna

How to use autowired class methos as task

Back to top button