Quartz: The Preferred Java Scheduling Framework

Quartz: The Preferred Java Scheduling Framework

▼ Click the card below to follow me

▲ Click the card above to follow me

Quartz: The Preferred Java Scheduling Framework

In software development, there are often requirements for scheduled tasks, such as collecting data every midnight, sending email reminders periodically, or synchronizing data at regular intervals. When it comes to Java scheduling frameworks, Quartz is definitely the most powerful and popular choice. I have been using it for many years and I think it works exceptionally well.

Core Concepts

When talking about Quartz, we must first understand a few key concepts:

Job is the specific task you want to execute; all the work happens here. For example, sending emails or generating reports are all defined here.

Trigger is the trigger that defines when to execute the job. You can set fixed times, periodic executions, or even use a complete cron expression; it’s entirely up to you.

Scheduler is the manager that is responsible for associating the Job and Trigger together and managing the scheduling.

Let’s look at a basic example:

public class EmailJob implements Job {
    @Override
    public void execute(JobExecutionContext context) {
        System.out.println("Sending email! Time: " + new Date());
    }
}
// Create job
JobDetail job = JobBuilder.newJob(EmailJob.class)
    .withIdentity("emailJob", "group1")
    .build();
// Create trigger
Trigger trigger = TriggerBuilder.newTrigger()
    .withIdentity("trigger1", "group1")
    .startNow()
    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
        .withIntervalInSeconds(10)
        .repeatForever())
    .build();
// Create scheduler
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);

Trigger Types

Quartz supports several types of triggers, each suited for different scenarios:

SimpleTrigger: A simple trigger that sets a time interval for execution. It is suitable for tasks with a fixed frequency.

CronTrigger: This is powerful, supporting cron expressions, allowing you to schedule tasks flexibly. For example, “0 0 12 * * ?” executes once every day at noon, and it’s that simple.

Friendly reminder: cron expressions may seem simple, but writing them incorrectly can lead to issues. I once mistakenly set a task to execute every second instead of every minute, which almost crashed the server…

Job Persistence

Quartz supports storing job information in a database, so even if the program restarts, the job configurations won’t be lost.

Properties props = new Properties();
props.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
props.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
props.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
props.put("org.quartz.jobStore.dataSource", "myDS");
// Data source configuration
props.put("org.quartz.dataSource.myDS.driver", "com.mysql.jdbc.Driver");
props.put("org.quartz.dataSource.myDS.URL", "jdbc:mysql://localhost:3306/quartz");
props.put("org.quartz.dataSource.myDS.user", "root");
props.put("org.quartz.dataSource.myDS.password", "123456");

Job Listeners

Sometimes we want to know when a job starts, when it ends, and whether it was successful. In such cases, we need to use listeners:

public class MyJobListener implements JobListener {
    public String getName() {
        return "My Listener";
    }
    public void jobToBeExecuted(JobExecutionContext context) {
        System.out.println("Job is about to start!");
    }
    public void jobExecutionVetoed(JobExecutionContext context) {
        System.out.println("Job was vetoed!");
    }
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        System.out.println("Job has finished executing!");
    }
}

Distributed Jobs

In a distributed environment, the same job may be executed simultaneously by multiple nodes, which is not acceptable. Quartz provides cluster support, and you just need to configure it:

props.put("org.quartz.jobStore.isClustered", "true");
props.put("org.quartz.jobStore.clusterCheckinInterval", "20000");

After working with it for so many years, I truly believe Quartz is very useful. However, there are a few points to keep in mind: do not let job execution times be too long, ensure fault tolerance, and log everything thoroughly. After all, system stability is the most important; you don’t want to be lost when issues arise.

The code is not difficult; the key is to understand the function of each component, like building blocks—just piece them together.

Previous Reviews

◆ FastJson: Alibaba’s Open Source JSON Parsing Library

◆ Netty: Asynchronous Network Application Framework Essential for High-Performance Network Programming

◆ EasyExcel: Say Goodbye to POI: A Faster and More Memory-Efficient Excel Processing Tool

Like and Share

Quartz: The Preferred Java Scheduling Framework

Let Money and Love Flow to You

Leave a Comment