Thursday, May 10, 2018

Quartz Scheduler Introduction

Quartz is an open source scheduling library which can be easily integrated into Java apps. It can schedule and execute several thousands of jobs.

To add Quartz to the app, add the below dependencies to the maven file.

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.3.0</version>
</dependency>
  <dependency>
      <groupId>org.quartz-scheduler</groupId>
      <artifactId>quartz-jobs</artifactId>
      <version>2.3.0</version>
  </dependency>

If we want to add the libraries directly, then the latest version of Quartz library can be downloaded from the below location.


Download the latest version of Quartz and extract it on the local system.
You will need to add the quartz, quartz-jobs, slf4j-api, slf4j-log4j12 and log4j jars to your classpath to use Quartz library.
If we want to use a database to store the job information, then we need to add c3p0 jar, otherwise, it is not needed.

There are 6 key classes/interfaces from Quartz that we need to understand to use Quartz
1.       Scheduler
2.       Job
3.       JobDetail
4.       Trigger
5.       JobBuilder
6.       TriggerBuilder

Scheduler:

The Scheduler maintains the jobs, triggers execution, can pause or stop the jobs from the executing.
So to start executing the jobs, you need to instantiate the Scheduler and start it. If the scheduler is not started, then the jobs won’t be executed/triggered even if they are scheduled.

We need to add the below 3 lines of code to get ready to use Quartz Scheduler.




Job:

All the classes that we want to schedule have to implement the Job Interface.
It has only one method ‘execute’ which is executed when the job is triggered.



Now we will create a job, create a trigger and schedule it.
The below code creates a job detail, a trigger to run every 10 seconds and schedules it.




I updated the SampleJob Class to print the time at which it is executed.




If we run the project, we can see that the execute method in SampleJob class is executed every 10 seconds.



The sample code is available on GitHub.



No comments:

Post a Comment