Quartz Scheduler + Spring Boot Example.
Integration of Quartz scheduler with Spring boot. Java Quartz scheduler cron expression example. Spring quartz scheduler postgresql database example.
Quartz Scheduler:
- Quartz is a richly featured, open source Job scheduling library.
- Quartz can be used to create simple or complex schedules for executing multiple jobs.
- Using quartz library, job can be schedule which can be executed instantly or to be executed later point of time.
- Quartz also accepts cron expression using which complex jobs can be scheduled like
"Run job after every 5 minutes" or "Run job every week on monday at 3 PM" etc.
- Spring boot is (Spring + Configuration) bundle which helps you to develop application faster.
- Spring boot take care of many configurations and helps developer focus on business.
- It includes an embedded tomcat (or jetty) server.
Spring Boot and Quartz Scheduler in Action.
Complete source code of Quartz Scheduler with Spring Boot:
Download Sample app from Github Page:
https://github.com/javabypatel/spring-boot-quartz-demo
Sample application direct download link:
https://github.com/javabypatel/spring-boot-quartz-demo/archive/master.zip
Example uses,
- Spring Boot 1.5.7
- Quartz 2.2.3
- PostgreSQL 9.4.1208
- Angular2
- Schedule Simple Quartz Job.
- Schedule Cron Quartz Job.
- Pause Quartz Job.
- Resume Quartz Job
- Edit Quartz Job.
- Delete Quartz Job.
- Unschedule Quartz Job.
- Stop Quartz Job.
- Check if Job is currently Running.
- Get the current state of Quartz Job.
- Get the list of all Scheduled Jobs.
- Job and Trigger Listeners for doing any operations before and after job starts, Listeners also hels in taking any action in case of job misfires due to application shutdown etc.
Quartz Scheduler Working.
Quartz work on concept of Jobs and Triggers.
- Job is anything that need to be executed when event occurs.
- Trigger is basically a event which contains time as when this event should occur.
There are 2 types of trigger,
- Simple Trigger
- Cron Trigger
For example, if you want the trigger to fire at exactly 11:23:54 AM on January 13, 2015, or if you want it to fire at that time, and then fire five more times, every ten seconds.
Cron Trigger: CronTrigger is often more useful than SimpleTrigger, It is used for scheduling jobs having complex time like if you need to execute job that recurs based on calendar-like notions, rather than on the exactly specified intervals.
With CronTrigger, you can specify firing-schedules such as "every Friday at noon", or "every weekday and 9:30 am", or even "every 5 minutes between 9:00 am and 10:00 am on every Monday, Wednesday and Friday during January".
Below are the few quartz methods that are used in example.
package com.javabypatel.demo.service; import java.util.Date; import java.util.List; import java.util.Map; import org.springframework.scheduling.quartz.QuartzJobBean; public interface JobService { //Schedule one time job. boolean scheduleOneTimeJob(String jobName, Class<? extends QuartzJobBean> jobClass, Date date); //Schedule cron recurring job. boolean scheduleCronJob(String jobName, Class<? extends QuartzJobBean> jobClass, Date date, String cronExpression); //Update one time job. boolean updateOneTimeJob(String jobName, Date date); //Update cron recurring job. boolean updateCronJob(String jobName, Date date, String cronExpression); //Unschedule scheduled job. boolean unScheduleJob(String jobName); //Delete a job. boolean deleteJob(String jobName); //Pause a job. boolean pauseJob(String jobName); //Resume a job. boolean resumeJob(String jobName); //Start a job instantly. boolean startJobNow(String jobName); //Check if job is already Running. boolean isJobRunning(String jobName); //Get list of all scheduled/Running jobs. List<Map<String, Object>> getAllJobs(); //Check if job with given name is present. boolean isJobWithNamePresent(String jobName); //Get the current state of job. String getJobState(String jobName); //Stop a Job. boolean stopJob(String jobName); }
Demo application also explains Quartz listeners, There are 2 types of listeners in quartz.
- Quartz Job Listeners.
- Quartz Trigger Listeners.
If you want to perform any task before job starts or when job completes or when trigger got misfired due to application shutdown, Quartz listeners will be helpful.
Download Sample app from Github Page:
https://github.com/javabypatel/spring-boot-quartz-demo
Sample application direct download link:
https://github.com/javabypatel/spring-boot-quartz-demo/archive/master.zip
Quartz Scheduler + Spring Boot + Angular2 Project Setup in Eclipse.
- Download the project from github.
- Import the project in Eclipse using "Import" > "Existing Maven Project".
- Once import is done properly and all dependencies are downloaded, project will look like below,
Running application in your Environment
After setting project in Eclipse,
- Sample application uses PostgreSQL database, so if you wish to use the same, Install PostgreSQL database server. (If you are planning to use other database then make respective changes in pom.xml for loading appropriate database driver, in application.properties file for providing database path and in quartz.properties for loading respective Delegate class)
- pom.xml.
<!-- PostgreSQL driver dependency (Change below Postgresql driver dependency to driver of your database vendor.)--> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.4.1208</version> <scope>runtime</scope> </dependency>application.properties
#--------------Enter Your Database Details below -------------- ####### SPRING JPA ############ spring.jpa.database=POSTGRESQL ####### SPRING JPA ############ ####### POSTGRES ############ spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.url=jdbc:postgresql://localhost:5432/scheduledemo spring.datasource.username=postgres spring.datasource.password=admin ####### POSTGRES ############quartz.properties
#--------------Enter appropriate Database Delegate class here -------------- org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
- If your Delegate class is from below use that else you need to find in Quartz site.
you can see in "org.quartz.impl.jdbcjobstore" package or in its sub-packages for all supporting Delegates.
- DB2v6Delegate (for DB2 version 6 and earlier)
- HSQLDBDelegate (for HSQLDB),
- MSSQLDelegate (for Microsoft SQLServer)
- PostgreSQLDelegate (for PostgreSQL),
- WeblogicDelegate (for using JDBC drivers made by Weblogic)
- OracleDelegate (for using Oracle).
- Create database name "quartzdemoapp" (if you want to use any other name then give the same database name in application.properties file by replacing "quartzdemoapp" by that name)
- Open command prompt in admin mode.
- Go to "ui-app" folder and execute "npm install" command as shown below, (Make sure you have node and npm installed.)
- Go to "ui-app" folder and execute "npm run server" command as shown below,
This step will start server and ui-app will be deployed. - Open the browser and hit http://localhost:8080/ you will see the application UI as shown above which will be used to schedule both simple and cron quartz job.
- Start the Spring-boot application by clicking on "SpringBootQuartzAppApplication.java" > Right click, Run as, "Java Application"
Note: Server will be hosted on localhost and port as 7080. (http://localhost:7080/)
- Client application is listening on port 8080.
- Server application is listening on port 7080.
server.port=your_application_port
If you don't want to run 2 application separately, then transpile the typescript files to javascript and put those files in your web application as shown below,
For converting typescript files to javascript files,
- Open command prompt, navigate to ui-app folder and run "npm run build".
- After above step you will see "target" folder created inside "ui-app" folder, copy those files inside target folder and paste it in your web application outside WEB-INF folder and run the server application.
Configuration files.
There are 3 configuration files,
- application.properties
- data.sql
- quartz.properties
application.properties :
It contains configuration for server and database as shown below,
server.port=7080 //Server will be listening on port 7080 spring.application.name=Scheduledemo ####### SPRING JPA ############ spring.jpa.database=POSTGRESQL spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop ####### SPRING JPA ############ ####### POSTGRES ############ spring.datasource.driver-class-name=org.postgresql.Driver #create the database by name "quartzdemoapp", here I am using postgresql running on port 5432. #if you want other database, change the url. spring.datasource.url=jdbc:postgresql://localhost:5432/quartzdemoapp #put your database username below spring.datasource.username=postgres #put your database password below spring.datasource.password=admin ####### POSTGRES ############
data.sql :
Quartz require jobs and triggers to be stored in database.
data.sql contains SQL scripts that creates tables required by quartz to manage scheduler.
quartz.properties :
org.quartz.scheduler.instanceName=springBootQuartzApp org.quartz.scheduler.instanceId=AUTO org.quartz.threadPool.threadCount=5 //number of concurrent jobs that can be run. org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate org.quartz.jobStore.useProperties=true org.quartz.jobStore.misfireThreshold=60000 //if job is delayed by 1 minute, don't consider it as misfire. org.quartz.jobStore.tablePrefix=qrtz_ //prefix used for all quartz related tables org.quartz.jobStore.isClustered=false org.quartz.plugin.shutdownHook.class=org.quartz.plugins.management.ShutdownHookPlugin org.quartz.plugin.shutdownHook.cleanShutdown=TRUE
You may also like to see
Compress a given string in-place and with constant extra space.
Check whether a given string is an interleaving of String 1 and String 2.
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord.
Serialize and Deserialize a Binary Tree
Advanced Multithreading Interview Questions In Java
Skyline Problem in Java.
Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted
Count trailing zeros in factorial of a number
When to use SOAP over REST Web Service. Is REST better than SOAP?
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.
No comments:
Post a Comment