Quartz SchedulerSchedulers play a key role of running batch processes in software applications. As a matter of fact Java language supports several key frameworks that assist software developers in dynamic job scheduling. Fulcrum Scheduler, Oddjob Scheduler, JDRing, Quartz Scheduler and J2EE Scheduler are some of the popular job schedulers. Out of all these, Quartz Scheduler is the most widely used job scheduler, as it offers impressive features including dynamic job scheduling and it is comparatively easier to use than other job schedulers.

Quartz is an advanced and powerful dynamic job scheduling framework (open source). It allows software developers to schedule jobs at a desired time. Furthermore, it provides provisions to edit, pause/resume and delete the scheduled job. Utilizing Quartz, software developers can create simple as well as complex schedules to execute thousands of jobs.

In this blog post, we will learn ‘How to schedule a job dynamically using the Quartz Scheduler’. Subsequently, we will also figure out the process to edit, pause/resume and delete scheduled jobs. We have considered a use case, which helps readers easily understand the process of scheduling jobs using Quartz Scheduler. As a software developer, if you are required to schedule jobs on daily, weekly, monthly or yearly basis, it is possible to execute the same using Quartz scheduler.

Job Schedule Frequencies

Below are some of the job schedule frequencies that can be setup using Quartz Scheduler:

  1. Daily
  2. Weekly
  3. Monthly
  4. Yearly

Job Schedule Recurrence Options

Quartz Scheduler further allows software developers to define the end recurrence options. Below are the three end recurrence options available in Quartz:

  1. Never End
  2. End After <No. of Occurrences>
  3. End By <Particular Date>

Appointment Recurrence Schedule - Quartz Scheduler

Solution Approach

In order to create the above job schedule frequencies with the mentioned end recurrence, software developers have to create a user interface using jQuery’s recurrenceinput.js library, Google’s RFC RRULE jar and Quartz Job Scheduler API. The recurrenceinput.js library captures the user selection in the form of RRULE syntax. The recurring schedule is captured as mentioned below:

RRULE:FREQ=WEEKLY;BYDAY=MO,WE;COUNT=4

Using Google’s RFC RRULE API, developers can parse the recurrent rule(rrule) and subsequently, by making use of custom logic convert it to Quartz’s CRON expression. Below is a step-by-step guide that would help developers achieve the above mentioned activity:

Step 1- How to Configure Quartz Scheduler?

The below code helps developers to configure the Quartz Scheduler:

<bean id="schedulerFactoryBean"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey">
<value>applicationContext</value>
</property>
<property name="configLocation" value="classpath:quartz.properties" />
<property name="overwriteExistingJobs" value="true" />
</bean>

applicationContextSchedulerContextKey – This property is used to pass a message to the Quartz Scheduler i.e. how and where to find Spring’s applicationContext. Furthermore, while executing a job, the Quartz Scheduler can access Spring beans using scheduler context. Here’s the code:

ApplicationContext appContext= jobExecutionContext.get(“applicationContextSchedulerContextKey”)

quartz.properties – This function is used to define all Quartz Scheduler properties; here are few examples of these properties (jobStore, datasource, threadPool, plugin, etc.).

Step 2 – How to Implement a Quartz Scheduler Job?

In order to implement a Quartz Scheduler Job, developers should make use of the Job class to implement the execute(JobExecutionContext) method of the Quartz Job interface. The Job class throws JobExecutionException, if an error occurs during job execution, JobExecutionContext should be populated with all the required information to run the job, while adding/editing a job. Below is the sample job code, which would help us understanding the concept better:

Public class MyJob implements Job{
@Override
 public void execute(final JobExecutionContext context)throws JobExecutionException {
 JobDetail jobDetail = context.getJobDetail();
 Long reportIdToRun =jobDetail.getKey();
 // do the actual job logic here. May be running a report, sending an
 // email, purging file system directory, etc.
 }
 }

Step 3 – How to Add a New Job to Quartz Scheduler?

To add a new job to the Quartz Job Scheduler for dynamic job scheduling, developers have to make use of JobDetail and Trigger components. The JobDetail interface is created using a unique key and a Job class, whereas the Trigger component is created using a unique trigger key. Lastly, schedules are created using TriggerBuilder with start and end dates. Here’s a sample job code that helps us gain a better understanding on the process of adding a new job schedule:

scheduler = schedulerFactoryBean.getScheduler();
JobKey jobKey = reportIdToRun; //
JobDetail jobDetail= newJob(MyJob.class).withIdentity(jobKey).build();
Trigger trigger= newTrigger().withIdentity(triggerKey).withSchedule(cronSchedule(cronExpression)).startAt(startDate).endAt(endDate).build()
scheduler.scheduleJob(jobDetail, trigger);

We have learnt the process of adding a job to Quartz Scheduler in three simple steps. Now, let’s figure out the process of editing, pausing, and deleting existing jobs in Quartz Scheduler.

How to Edit an Existing Job?

In order to edit/update an existing job in Quartz Scheduler developers need to:

  1. Update the job details
  2. Update the trigger details

Here’s the code, which would allow developers to complete this activity:

scheduler.addJob(updatedJobDetail, true, true); // 2nd parameter true means updating the existing job with the updated one.
scheduler.rescheduleJob(oldTriggerKey, newTrigger);
How to Pause/Resume an Existing Job?

In order to Pause/Resume an existing job in Quartz Scheduler, developers can use the below code:

scheduler.pauseJob(jobKey);
scheduler.resumeJob(jobKey); // the job will be resumed based on the quartz misfire instructions.
How to Delete an Existing Job?

Deleting an existing job in Quartz Scheduler is a fairly easy task. Below is the code that would allow developers to delete an existing job:

  • Unschedule the job
  • Delete the job
scheduler.unscheduleJob(jobKey);
scheduler.deleteJob(jobKey);

Technology Stack

To demonstrate the functioning of Quartz Scheduler, we have utilized the below tools and technologies:

  • Quartz 2.2.1
  • Spring Framework 3.2.12
  • jQuery recurrence widget (recurrenceinput.js)
  • Google’s iCalendar RFC 2445

Conclusion

By and large, Quartz Scheduler has gained massive popularity among Java developers due to its flexibility and dynamic scheduling capabilities. No wonder, it is one of the most preferred job schedulers for dynamic job scheduling. I assume this blog would help Java developers to gain a good understanding of Quartz Scheduler for dynamic job scheduling. If you have any queries or inputs, please feel free to post your comments.