Over a million developers have joined DZone.

Integrating Quartz With Spring

Quartz is job scheduler backed up by most popular RDBMSes. It is really convenient and gets integrated with Spring quite easy.

Is iPaaS solving the right problems? Not knowing the fundamental difference between iPaaS and dPaaS could cost you down the road. Brought to you in partnership with Liaison Technologies.

When it comes to scheduling jobs in a Java application, Quartz is the first tool that comes into consideration.

Quartz is job scheduler backed up by most popular RDBMSes. It is really convenient and gets integrated with Spring quite easy.

In order to create the Quartz schema you have to download the Quartz distribution and extract the folder located in quartz-2.2.3/docs/dbTables/.

Choose the Quartz schema according to the database that you use. In our case we will use a local h2 database therefore I will use the tables_h2.sql schema.

In order to avoid any manual SQL actions, I will use the Spring boot database initialization feature.

Let’s start with our gradle file.

group 'com.gkatzioura'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
buildscript {
    repositories {
    dependencies {
apply plugin: 'idea'
apply plugin: 'spring-boot'
repositories {
dependencies {
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.3.3.RELEASE'
    compile group: 'org.springframework', name: 'spring-context-support', version: '4.2.4.RELEASE'
    compile group: 'org.springframework', name:'spring-jdbc', version: '4.2.4.RELEASE'
    compile group: 'org.quartz-scheduler', name: 'quartz', version: '2.2.3'
    compile group: 'ch.qos.logback', name: 'logback-core', version:'1.1.3'
    compile group: 'ch.qos.logback', name: 'logback-classic',version:'1.1.3'
    compile group: 'org.slf4j', name: 'slf4j-api',version:'1.7.13'
    compile group: 'com.h2database', name: 'h2', version:'1.4.192'
    testCompile group: 'junit', name: 'junit', version: '4.11'

Apart from the Quartz, Spring, and h2 dependencies, we add the spring-jdbc dependencies since we want to have the database initialized through spring.

We will also add an application.yml file:

    continueOnError: true
      instanceName: spring-boot-quartz-demo
      instanceId: AUTO
      threadCount: 5
  startDelay: 0
  repeatInterval: 60000
  description: Sample job
  key: StatisticsJob

Due to the schema creation statements (lack of create if not exists statements), I set spring.datasource.continueOnError to false. According to your implementation, the workaround will vary.

The application class:

package com.gkatzioura.springquartz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
 * Created by gkatzioura on 6/6/16.
public class Application {
    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication();
        ApplicationContext ctx = springApplication.run(Application.class,args);

The h2 datasource configuration needed by Quartz:

package com.gkatzioura.springquartz.config;
import org.h2.jdbcx.JdbcDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
 * Created by gkatzioura on 6/6/16.
public class QuartzDataSource {
    //Since it a test database it will be located at the temp directory
    private static final String TMP_DIR = System.getProperty("java.io.tmpdir");
    public DataSource dataSource() {
        JdbcDataSource ds = new JdbcDataSource();
        return ds;

In our case we want to send ‘spam’ emails every minute, so we define a simple email service:

package com.gkatzioura.springquartz.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
 * Created by gkatzioura on 6/7/16.
public class EmailService {
    private static final Logger LOGGER = LoggerFactory.getLogger(EmailService.class);
    public void sendSpam() {
        LOGGER.info("Should send emails");

I will also implement a SpringBeanJobFactory:

package com.gkatzioura.springquartz.quartz;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
 * Created by gkatzioura on 6/7/16.
public class QuartzJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
    private transient AutowireCapableBeanFactory beanFactory;
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        beanFactory = applicationContext.getAutowireCapableBeanFactory();
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        return job;

QuartzJobFactory will create the job instance and the will use the application context in order to inject any dependencies defined.

The next step is defining our job:

package com.gkatzioura.springquartz.job;
import com.gkatzioura.springquartz.service.EmailService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
 * Created by gkatzioura on 6/6/16.
public class EmailJob implements Job {
    private EmailService cronService;
    public void execute(JobExecutionContext context) throws JobExecutionException {

Last step is adding the Quartz config:

package com.gkatzioura.springquartz.config;
import com.gkatzioura.springquartz.job.EmailJob;
import com.gkatzioura.springquartz.quartz.QuartzJobFactory;
import org.quartz.SimpleTrigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
import javax.sql.DataSource;
import java.util.Properties;
 * Created by gkatzioura on 6/7/16.
public class QuartzConfig {
    private String instanceName;
    private String instanceId;
    private String threadCount;
    private Long startDelay;
    private Long repeatInterval;
    private String description;
    private String key;
    private DataSource dataSource;
    public org.quartz.spi.JobFactory jobFactory(ApplicationContext applicationContext) {
        QuartzJobFactory sampleJobFactory = new QuartzJobFactory();
        return sampleJobFactory;
    public SchedulerFactoryBean schedulerFactoryBean(ApplicationContext applicationContext) {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        Properties quartzProperties = new Properties();
        return factory;
    @Bean(name = "emailJobTrigger")
    public SimpleTriggerFactoryBean emailJobTrigger() {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        return factoryBean;
    @Bean(name = "emailJobDetails")
    public JobDetailFactoryBean emailJobDetails() {
        JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
        return jobDetailFactoryBean;

What we did is creating a scheduler factory bean using the QuartzJobFactory we defined and we registered the triggers needed for our jobs to run. In our case we implemented a simple trigger running every minute.

You can find the source code on GitHub

Discover the unprecedented possibilities and challenges, created by today’s fast paced data climate and why your current integration solution is not enough, brought to you in partnership with Liaison Technologies.

quartz ,local ,database ,spring boot

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}