seon99il

Spring

Learn about the Quartz Scheduler

3 min read

java : 11 springBoot : 2.7.5

Part 1 : Learn about the Quartz Scheduler Part 2 : Implementing Scheduler with Quartz Scheduler with SpringBoot Part 3 : Implement sending alerts at specific times per user with QuartzScheduler

I will write a series of what I learned while implementing a push notification service using Quartz Scheduler.

This article explains the theoretical content and the setting of the environment.

When you work on a project, you sometimes have to run a method at a certain period or cycle. Most people would have used spring scheduler.

I’m going to use the Quartz Job Scheduler to create simple or complex schedules.

What is Quartz?

Quartz is a job scheduling library developed by a company called Terracotta. Quartz can run tens to thousands of tasks and supports complex scheduling in simple interval formats or Cron expressions. For example, you can specify what to do every Friday at 1:30am, what to do on the last day of the month, or what to do five minutes before a specific time.

Pros and Cons

As always, every technology has its pros and cons.

Pros

  1. Provides clustering between schedulers based on DB
  2. Supports system fail-over and random load distribution
  3. Provides In-memory Job Scheduler
  4. ShutdownHookPlugin: catches the JVM shutdown event and notifies the scheduler of the shutdown
  5. LoggingJobHistoryPlugin: it can be useful for debugging by leaving a log of Job execution
  6. Enables dynamic scheduling: you can make the work that ran at 9 o’clock today run at 10 o’clock tomorrow without any modification

Cons

  1. It provides clustering capabilities, but because it is a simple random approach, load balancing between clusters is not complete.
  2. It does not provide a UI, so it must be implemented directly if necessary.
  3. History for scheduling execution is not archived.

Quartz Architecture and Components

Job

An interface to be implemented by components that you wish to have executed by the scheduler.

@Slf4j
@Component
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class SampleJob implements Job {

    @Autowired
    private TestRepository testRepository;

    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        System.out.println(this.getClass().getName() + "Sample Job Start! [ "
                            + LocalDate.now() + " ]");
    }
}

JobDataMap

The JobDataMap is an object that stores information that is available when the Job instance runs.

JobDetail

It is an object that contains information for executing the Job. Includes Job name, group, JobDataMap attribute, etc.

public <T extends Job> JobDetail buildJobDetail(Class<? extends Job> job, SampleJobRequest request) {

        JobDataMap jobDataMap = new JobDataMap(); // job Data Map
        jobDataMap.put("executeCount", 1); // put Data

        return JobBuilder.newJob(job)
                .withIdentity(request.getJobName())
                .withDescription(request.getJobDescription())
                .usingJobData(jobDataMap)
                .build();
    }

Trigger

I think this is the core object of the Quartz Scheduler. A Trigger contains scheduling conditions (ex. number of iterations, start time) to execute the job, and the scheduler performs the job based on this information.

The Relationship Between Trigger and Job

  • Trigger (1) : Job (1) One Trigger must be designated for one Job.
  • Trigger (N) : Job (1) One Job can be run multiple times at different times.
  • Trigger (1) : Job (N) (X) One Trigger cannot have more than one Job.

Cron trigger and simple trigger

  • SimpleTrigger You can run the Job at a specific time.
private Trigger buildTrigger() {
        SimpleTriggerFactoryBean triggerFactory = new SimpleTriggerFactoryBean();

        triggerFactory.setName("SimpleTriggerName");
        triggerFactory.setGroup("Group");
        triggerFactory.setStartTime(localTimeToDate(LocalTime.now().plusHours(2)));
        triggerFactory.setRepeatCount(0);
        triggerFactory.setRepeatInterval(0);

        triggerFactory.afterPropertiesSet();
        return triggerFactory.getObject();

    }
  • CronTrigger Create a trigger using cron. It can make more complex schedules (ex. running every few minutes from 2 pm to 4 pm on the first day of every month).
private Trigger buildCronTrigger() {
        CronTriggerFactoryBean CrontriggerFactory = new CronTriggerFactoryBean();
        CrontriggerFactory.setName("CronName");
        CrontriggerFactory.setGroup("Group");
        CrontriggerFactory.setCronExpression("2 * * * * *");
        CrontriggerFactory.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);

        try {
            CrontriggerFactory.afterPropertiesSet();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return CrontriggerFactory.getObject();
    }

Misfire Instructions

Misfire means an operation failure. It occurs when the Scheduler exits or when no threads are available in the thread pool. Various policies are supported for how the Scheduler handles misfired Triggers.

  • MISFIRE_INSTRUCTION_FIRE_NOW
  • MISFIRE_INSTRUCTION_DO_NOTHING

Listener

A Listener is an interface provided by Quartz to receive events from the Scheduler.

  • JobListener Operates when a job starts and ends.
  • TriggerListener You can receive an event when a trigger fires or fails, or when a trigger completes.

JobStore

Jobs and Triggers can be stored in memory or in a DB.

Quartz Components

See the link below for more information.

Quartz Scheduler Model - Java Articles

In the next article, I will explain how to implement it.

You can see the code on my GitHub.

GitHub - Seonggil-Jeong/QuartzScheduler-Sample

Previous posts

View all posts →

Comments