Monday, August 31, 2020

Introduction to Quartz Scheduler

When  you are implementing new functionality in Java, you may have to run a task in one of the following ways.

  • daily at 8.00AM. 

  • after every 10 minutes.

  • only weekends.

  • once a month or year.



You need to use a scheduler to fulfil this requirement and you can select one of the following.


  • Java Interface - java.util.concurrent.ScheduledExecutorService

  • Java Interface - org.springframework.scheduling.TaskScheduler 

  • Quartz Scheduler - org.quartz 

  • java util class - java.util.TimerTask


In this article,  I am going to describe what is the Quartz Scheduler and how can you use that.

Quartz Scheduler




Quartz is an open-source job scheduling library that can be integrated with any Java application since it licensed under the Apache 2.0 license.


Features of Quartz Scheduler


Runtime Environments - Quartz can run as a stand-alone program or cluster of stand-alone programs with load-balance and fail-over capabilities.


Job Scheduling - Jobs can be scheduled to run when a given trigger occurs. Triggers can be created to run any time in any order. 


Job Persistence - All Jobs and triggers configured as "non-volatile" can be stored in a relational database via JDBC. And all non-persistent jobs and triggers can be stored in RAM.


Transactions - Quartz can participate in JTA transactions which allows to perform distributed transactions which access and update data on two or more networked computer resources.


Monitoring - Applications can catch scheduling events to monitor or control job/trigger behaviour by implementing one or more listener interfaces.


Main components of Quartz Scheduler

Job 


Quartz provides a Job interface to implement a single method named execute(). You need to add an implementation inside that method which will do the scheduled task. 


When a job's trigger fires, the scheduler invokes the execute method and runs the code inside that.



@Component

public class ExampleJob implements Job {

 

    @Autowired

    private ExampleJobService exJobService;

 

    public void execute(JobExecutionContext context) throws JobExecutionException {

        exJobService.executeExampleJob();

    }

}



JobDetail and JobBuilder


Quartz does not store an actual instance of the job class. Instead, it allows to define an instance of the Job using the JobDetail class. It conveys the detailed properties of a given Job instance. JobDetails are to be created/defined with JobBuilder. The job's class must be provided to the JobDetail so that it knows the type of job to be executed.


 public JobDetail jobDetail() {


        return JobBuilder.newJob().ofType(ExampleJob.class)

                .storeDurably() //Job remain stored after it is orphaned

                .withIdentity("Example_Job") //Use a JobKey with the given name and default group //to identify the JobDetail

                .withDescription("Invoke example job") // Set a description of the Job

                .build(); //Produce the JobDetail instance

    }


JobStore


JobStore provides the storage mechanism for the jobs, triggers. and all the data relevant to the job scheduler. To save all the things in volatile nature, you can use  RAMJobStore. If you need persistent stores, you can use JobStoreTX or JobStoreCMT.


JobStore can be configured in quartz.properties file as follows.


Ex - org.quartz.jobStore.class=org.quartz.simpl.RAMJobStore

       org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX



Trigger


Trigger objects are used to start the execution of jobs. There are different types of triggers like SimpleTrigger and CronTrigger for different scheduling needs.


 SimpleTrigger is used to execute a job 

  • starts at a given time.

  • repeat N times.

  • with a delay between each execution.


Ex - Start the job named “Example_Job” at a given time and repeat after every 2 hours forever.


 SimpleTrigger trigger = (SimpleTrigger) newTrigger()

    .withIdentity("trigger1") //

    .withDescription("Trigger Invoke example job") //

    .startAt(myStartTime) // start time

    .withSchedule(simpleSchedule().withIntervalInHours(2) .repeatForever())

    .forJob("Example_Job") //Start the job named “Example_Job

    .build();



CronTrigger is used to start the execution of job-based on calendar-like schedules.


Ex - Start the job named “Example_Job” every day at 10.35 A.M


  trigger = newTrigger()

    .withIdentity("sampleTrigger")

    .withSchedule(cronSchedule("0 35 10 * * ?"))

    .forJob("Example_Job") //identify job with  its JobKey

    .build();


There is a clear difference between the Job and Trigger.  Job defines the task that needs to be done in a scheduled time. And trigger will invoke a  job at the scheduled time to do what job wants.


Scheduler


The Scheduler interface is the main API for interfacing with the Quartz job scheduler.


A Scheduler can be instantiated with a SchedulerFactory.   After created it can be used to add, remove and list Jobs and Triggers.



SchedulerFactory schedulerFactory = new StdSchedulerFactory();

Scheduler scheduler = schedulerFactory.getScheduler();


Initially, the Scheduler is in “stand-by” mode. You have to invoke its start method to start the threads that fire the execution of jobs.


scheduler.start();



Resource - http://www.quartz-scheduler.org/


No comments:

Post a Comment

How to send Slack notification using a Python script?

 In this article,  I am focussing on sending Slack notifications periodically based on the records in the database. Suppose we have to monit...