Quartz

Java Quartz Job Parameters Example

In this article we will learn how to pass parameters in Quartz Job.

1. Introduction

Quartz is a richly featured, open-source job scheduling library that can be integrated within virtually any Java application – from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do.

Quartz can run embedded within another free-standing application. Quartz can be instantiated within an application server (or servlet container), and participate in XA transactions. Quartz can run as a stand-alone program (within its own Java Virtual Machine), to be used via RMI. Quartz can be instantiated as a cluster of stand-alone programs (with load-balance and fail-over capabilities) for the execution of jobs

2. Code

In this section, we will write the code to show how we can pass parameters in the job.

2.1 Job

First, we will create a simple job. This will implements the org.quartz.Job interface. The execute method will get the job data map from the context and will print the parameter values which are set in the scheduler.

JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
String first_param = dataMap.getString("PARAM_1_NAME");
String second_param = dataMap.getString("PARAM_2_NAME");

JobExecutionContext is a context bundle containing handles to various environment information, that is given to a JobDetail instance as it is executed, and to a Trigger instance after the execution completes.

The JobDataMap found on this object serves as a convenience – it is a merge of the JobDataMap found on the JobDetail and the one found on the Trigger, with the value in the latter overriding any same-named values in the former. It is thus considered a ‘best practice’ that the execute code of a Job retrieve data from the JobDataMap found on this object.

ExampleJob.class

package org.javacodegeeks;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;

import java.time.LocalDateTime;

public class ExampleJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        System.out.println("Job executed at: " + LocalDateTime.now().toString());
        JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        //fetch parameters from JobDataMap
        String first_param = dataMap.getString("PARAM_1_NAME");
        String second_param = dataMap.getString("PARAM_2_NAME");
        System.out.println("First parameter value : " + first_param);
        System.out.println("Second parameter value : " + second_param);
    }
}

2.2 Scheduler

In this section, we will see how to schedule the job and how to pass the parameter. First we need to get the scheduler from the factory:

SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();

The SchedulerFactory provides a mechanism for obtaining client-usable handles to Scheduler instances.

Scheduler is the main interface of a Quartz Scheduler. A Scheduler maintains a registry of JobDetails and Triggers. Once registered, the Scheduler is responsible for executing Job s when they’re associated Triggers fire (when their scheduled time arrives).

Scheduler instances are produced by a SchedulerFactory. A scheduler that has already been created/initialized can be found and used through the same factory that produced it. After a Scheduler has been created, it is in “stand-by” mode and must have its start() method called before it will fire any Jobs.

Jobs are to be created by the ‘client program’, by defining a class that implements the Job interface. JobDetail objects are then created (also by the client) to define individual instances of the Job. JobDetail instances can then be registered with the Scheduler via the scheduleJob(JobDetail, Trigger) or addJob(JobDetail, boolean) method.

Triggers can then be defined to fire individual Job instances based on given schedules. SimpleTriggers are most useful for one-time firings, or firing at an exact moment in time, with N repeats with a given delay between them. CronTriggers allow scheduling based on time of day, day of the week, day of the month, and month of the year.

Jobs and Triggers have a name and group associated with them, which should uniquely identify them within a single Scheduler. The ‘group’ feature may be useful for creating logical groupings or categorizations of Jobs and Triggers. If you don’t have a need for assigning a group to a given Jobs of Triggers, then you can use the DEFAULT_GROUP constant defined on this interface.

Now we will create a new Job:

JobDetail job = newJob(ExampleJob.class).withIdentity("MyJobName", "MyJobGroup").build();

We will use the newJob() method JobBuilder class by passing the Job name. Now we will set parameters for this job:

job.getJobDataMap().put("PARAM_1_NAME", "PARAM_1_VALUE");
job.getJobDataMap().put("PARAM_2_NAME", "PARAM_2_VALUE");

Now let’s trigger the job to run after 5 seconds:

Date date = Date.from(LocalDateTime.now().plusSeconds(5).atZone(ZoneId.systemDefault()).toInstant());
Trigger trigger = newTrigger().withIdentity("MyTriggerName", "MyTriggerGroup").startAt(date).build();

Now tell quartz to schedule the job using our trigger:

scheduler.scheduleJob(job, trigger);

QuartzJobParamExample.java

package org.javacodegeeks;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

public class QuartzJobParamExample {

    public static void main(String[] args) {
        QuartzJobParamExample quartzJobParamExample = new QuartzJobParamExample();
        quartzJobParamExample.run();
    }

    private void run() {

        // First we must get a reference to a scheduler
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();

            // define the job and tie it to our HelloJob class
            JobDetail job = newJob(ExampleJob.class).withIdentity("MyJobName", "MyJobGroup").build();
            job.getJobDataMap().put("PARAM_1_NAME", "PARAM_1_VALUE");
            job.getJobDataMap().put("PARAM_2_NAME", "PARAM_2_VALUE");

            // Trigger the job to run after 5 seconds
            Date date = Date.from(LocalDateTime.now().plusSeconds(5).atZone(ZoneId.systemDefault()).toInstant());
            Trigger trigger = newTrigger().withIdentity("MyTriggerName", "MyTriggerGroup").startAt(date).build();

            // Tell quartz to schedule the job using our trigger
            scheduler.scheduleJob(job, trigger);
            System.out.println(job.getKey() + " will run at: "+ date);

            // Start up the scheduler (nothing can actually run until the scheduler has been started)
            scheduler.start();

            // wait long enough so that the scheduler as an opportunity to run the job!
            System.out.println("Waiting for 10 seconds");
            try {
                // wait 65 seconds to show job
                Thread.sleep(10*1000);
            } catch (Exception e) {
            }

            // Shutdown the scheduler
            scheduler.shutdown(true);

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

When you run the scheduler you will see the below output:

MyJobGroup.MyJobName will run at: Sat Aug 29 19:13:08 IST 2020
Waiting for 10 seconds
Job executed at: 2020-08-29T19:13:08.358
First parameter value : PARAM_1_VALUE
Second parameter value : PARAM_2_VALUE

3. Summary

In this article, we learned about Quartz Scheduler. We discussed what it is and what it is used for. We also discussed what are the important classes. At the end, we discussed how to pass parameters in the job using job data map.

4. Download the source code

Download
You can download the full source code of this example here: Java Quartz Job Parameters Example

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button