Quartz Cron Scheduler Spring Integration

Quartz Cron Scheduler

Quartz is open source job schedular library which can be integrated within any Java applications. It can be smallest stand alone application to largest web application system. It can be used to create complex to simple schedules for executing one, ten, hundreds or even tens thousands jobs. Jobs can be defined as java component that will may execute virtually anything you may want to do by program. It also includes many enterprise wide features such as support for clustering and JTA transactions. In this demo you will see how to create Quartz cron scheduler using java program. You could either create simple or cron scheduler where cron scheduler is more preferabel where you could control of scheduling on different time using configuration file so you don’t need to change your code everytime you change your schedule.

Note: I will create maven spring project and where cron shedule data will be read from property file and this project is developed using JDK 1.8.

  • Create maven project name: QuatzScheduler.
  • Final project structure:

Quartz Cron Scheduler Spring Integration

Many option are available to configure schedule to kick off jobs and below are some examples:

#Cron scheduler run every minute
0 0/1 * 1/1 * ? *

#Run job every 30 minute:
0 0/30 * 1/1 * ? *

#Run job everyday at 16:00 PM:
0 00 18 1/1 * ? *

#Run job everyday at multiple time start from 16:01,16:02… 21:01,21:02 etc..:
0 00,01,02,03 18,19,20,21 1/1 * ? *

#Run job every 15 minute:
0 0/15 * 1/1 * ? *

  • pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.javahonk</groupId>
	<artifactId>QuartzScheduler</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>QuartzScheduler</name>
	<url>http://maven.apache.org</url>

	<properties>
		<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
		<org.apache.log4j.version>2.1</org.apache.log4j.version>
	</properties>

	<dependencies>

		<!-- Application Context (depends on spring-core, spring-expression, spring-aop, 
			spring-beans) This is the central artifact for Spring's Dependency Injection 
			Container and is generally always defined -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>

		<dependency>
			<groupId>org.quickfixj</groupId>
			<artifactId>quickfixj-all</artifactId>
			<version>1.5.4</version>
		</dependency>

		<!-- Quartz scheduler -->
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.1.7</version>
		</dependency>

		<!-- Log4j -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>${org.apache.log4j.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${org.apache.log4j.version}</version>
		</dependency>

		<!-- slf4j jars -->

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>1.6.1</version>
		</dependency>
		
	</dependencies>


</project>
  • spring-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
	
	<context:annotation-config />
	<context:component-scan base-package="com.javahonk" />
	
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>Cron-Schedule.properties</value>				
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true"/>
	</bean>	

	<bean id="cronQuartzJob" class="com.javahonk.CronQuartzJob"/>
		
</beans>
  • Cron-Schedule.properties:
#Cron scheduler run every minute
cron.schedule.time= 0 0/1 * 1/1 * ? *

#Run job every minute: 0 0/1 * 1/1 * ? *
#Run job everyday at 16:00 PM: 0 00 18 1/1 * ? *
#Run job everyday at multiple time start from 16:01,16:02... 21:01,21:02 etc..: 0 00,01,02,03 18,19,20,21 1/1 * ? *
#Run job every 15 minute: 0 0/15 * 1/1 * ? *
  • CronQuartzJob.java:
package com.javahonk;

import java.time.LocalDateTime;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Java Honk
 *
 */
public class CronQuartzJob implements Job {
	
	@Value("${cron.schedule.time}")
	private String cronScheduleTime;
	
	private static final Logger LOGGER = LogManager.getLogger(CronQuartzJob.class.getName());
	
	public static void main(String[] args) {
		
		LOGGER.info("CronQuartzJob started.");	
		
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
		
		CronQuartzJob cronQuartzJob = (CronQuartzJob)context.getBean(CronQuartzJob.class);
		cronQuartzJob.startJavaHonkQuartzJob();
		
		((AbstractApplicationContext)context).close();
	}

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		
		LOGGER.info("Cron Quartz Job started at time: {}", LocalDateTime.now());
		System.out.println("Cron Quartz Job started at time: "+ LocalDateTime.now());

	}
	
	public void startJavaHonkQuartzJob() {

		try {

			JobDetail job = JobBuilder.newJob(CronQuartzJob.class).withIdentity("Java Honk Price Update", "Java Honk Data Cache").build();
			
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity("Java Honk Price Update", "Java Honk Data Cache")
					.withSchedule(CronScheduleBuilder.cronSchedule(cronScheduleTime)).build();

			Scheduler scheduler = new StdSchedulerFactory().getScheduler();
			scheduler.start();
			scheduler.scheduleJob(job, trigger);
			
		} catch (SchedulerException e) {
			LOGGER.error("Exception occured class name:-> "+ CronQuartzJob.class.getName()+ "method: startJavaHonkQuartzJob:-->{}", e);
		}

	}	

}
  • Output: As we have configured to run this Quartz scheduler every minute when you run this program you will see below output:

Quartz Cron Scheduler Spring Integration

  • For more information please visit Quartz documentation here

download Download Project:  QuartzScheduler

Leave a Reply

Your email address will not be published. Required fields are marked *