Introduction about Quartz Scheduler

Quartz Scheduler is a library that allows us to schedule a task to run at a certain time. By defining time or using Cron Expression that we often use to create Cron Jobs in Linux, Quartz Scheduler will help us trigger the tasks we want at a specific time or in some specific cases. How is it in details? Let’s learn about Quartz Scheduler in this tutorial!

First, I will create a new Maven project as an example:

Introduction about Quartz Scheduler

with Quartz Scheduler dependency as follows:

To work with Quartz Scheduler, you need to grasp three basic concepts:

Quartz Job: this concept is used to define the task we want to run. We will implement the org.quartz.Job interface to define this task.

Quartz Trigger is used to define the time we will run the task. As I said above, we can specify the time to run the task or use Cron Expression to define time by day, by month, by year.

Scheduler: by default, Quartz Job and Quartz Trigger don’t relate to each other, in order to use Quartz Trigger to trigger Quartz Job to run, we need to use the Scheduler object to do this.

Now we will try to implement a Quartz Job:

a Quartz Trigger:

In this Trigger section, the withIdentity() method is used to distinguish this trigger from other triggers in case you have multiple running triggers. If you do not declare this method, a random value will be generated.

Using the SimpleSchedulerBuilder, we can set the time for the Trigger to run, repeat or not?

As I said, we can also use Cron Expression to build Trigger. Example is as follows:

To build this Trigger, you need to have some knowledge about Cron Expression! Here, I am setting Trigger to run after every 5 seconds.

and using Scheduler to run the task as follows:

The result when running this example is as follows:

Introduction about Quartz Scheduler

You will see, every 5 seconds, our application will run the task of printing “Hello from Huong Dan Java” to the console.

Add Comment