In this post we will see how to schedule Jobs using Quartz Scheduler with Spring. Spring provides couple of classes that simplify the usage of Quartz within Spring-based applications.

Step 1: Provide Dependencies in Maven pom.xml

<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.websystique.spring</groupId>
<artifactId>SpringQuartzIntegrationExample</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>SpringQuartzIntegrationExample</name> <properties>
<springframework.version>4.2.4.RELEASE</springframework.version>
<quartz.version>2.2.1</quartz.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Transaction dependency is required with Quartz integration -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Quartz framework -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>${quartz.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
<showDeprecation>true</showDeprecation>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

Step 2: Configure Jobs in Quartz Scheduler

There are 2 ways to configure a Job in Spring using Quartz

A : Using MethodInvokingJobDetailFactoryBean

Really handy when you just need to invoke a method on a specific bean. This is the simplest among two.

<!-- For times when you just need to invoke a method on a specific object -->
<bean id="simpleJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="myBean" />
<property name="targetMethod" value="printMessage" />
</bean>

Above job configuration simply invokes printMessage method of bean myJobBean which is simple POJO

B : Using JobDetailFactoryBean

When you need more advanced setup, need to pass data to job, being more flexible.

<!-- For times when you need more complex processing, passing data to the scheduled job -->
<bean name="complexJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.**.spring.quartz.ScheduledJob" />
<property name="jobDataMap">
<map>
<entry key="anotherBean" value-ref="anotherBean" />
</map>
</property>
<property name="durability" value="true" />
</bean>

jobClass refers to a class which extends QuartzJobBean, an implementation of Quartz job interface. On invocation of this job, it’s executeInternal method gets called.
jobDataMap provides opportunity to pass some data to underlying job bean. In this case, we are passing a bean ‘anotherBean’ which will be used by ScheduledJob.

Below is the referred jobclass (ScheduledJob) implementation.

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean; import com.bianjq.spring.scheduling.AnotherBean; public class ScheduledJob extends QuartzJobBean{ private AnotherBean anotherBean; @Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
anotherBean.printAnotherMessage();
} public void setAnotherBean(AnotherBean anotherBean) {
this.anotherBean = anotherBean;
}
}

Step 3: Configure Triggers to be used in Quartz Scheduler

Trigger defines the time when scheduler will run your scheduled job. There are two possible trigger type:

A: Simple Trigger , using SimpleTriggerFactoryBean
You can specify start time, delay between triggers and repeatInterval(frequency) to run the job.

<!-- Run the job every 2 seconds with initial delay of 1 second -->
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="simpleJobDetail" />
<property name="startDelay" value="1000" />
<property name="repeatInterval" value="2000" />
</bean>

B: Cron Trigger , using CronTriggerFactoryBean

It’s more flexible and allows you to choose scheduled job at specific instance (time, day, date,..) and frequency in future.

<!-- Run the job every 5 seconds only on Weekends -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="complexJobDetail" />
<property name="cronExpression" value="0/5 * * ? * SAT-SUN" />
</bean>

Step 4: Configure SchedulerFactoryBean that creates and configures Quartz Scheduler

SchedulerFactoryBean glues together jobDetails and triggers to Configure Quartz Scheduler

<!-- Scheduler factory bean to glue together jobDetails and triggers to Configure Quartz Scheduler -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="simpleJobDetail" />
<ref bean="complexJobDetail" />
</list>
</property> <property name="triggers">
<list>
<ref bean="simpleTrigger" />
<ref bean="cronTrigger" />
</list>
</property>
</bean>

Below shown is complete context file for our example

src/main/resources/quartz-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.websystique.spring" /> <!-- For times when you just need to invoke a method on a specific object -->
<bean id="simpleJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="myBean" />
<property name="targetMethod" value="printMessage" />
</bean> <!-- For times when you need more complex processing, passing data to the scheduled job -->
<bean name="complexJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.websystique.spring.quartz.ScheduledJob" />
<property name="jobDataMap">
<map>
<entry key="anotherBean" value-ref="anotherBean" />
</map>
</property>
<property name="durability" value="true" />
</bean> <!-- Run the job every 2 seconds with initial delay of 1 second -->
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="simpleJobDetail" />
<property name="startDelay" value="1000" />
<property name="repeatInterval" value="2000" />
</bean> <!-- Run the job every 5 seconds only on Weekends -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="complexJobDetail" />
<property name="cronExpression" value="0/5 * * ? * SAT-SUN" />
</bean> <!-- Scheduler factory bean to glue together jobDetails and triggers to Configure Quartz Scheduler -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="simpleJobDetail" />
<ref bean="complexJobDetail" />
</list>
</property> <property name="triggers">
<list>
<ref bean="simpleTrigger" />
<ref bean="cronTrigger" />
</list>
</property>
</bean> </beans>

Step 5: Create simple POJO’s Task Beans used in this example

import org.springframework.stereotype.Component;

@Component("myBean")
public class MyBean { public void printMessage() {
System.out.println("I am called by MethodInvokingJobDetailFactoryBean using SimpleTriggerFactoryBean");
} }
import org.springframework.stereotype.Component;

@Component("anotherBean")
public class AnotherBean { public void printAnotherMessage(){
System.out.println("I am called by Quartz jobBean using CronTriggerFactoryBean");
} }

Step 6: Create Main, and Run the application

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class AppMain {
public static void main(String args[]){
AbstractApplicationContext context = new ClassPathXmlApplicationContext("quartz-context.xml");
} }

Run it as Java application, you will see following output.

INFO: Starting Quartz Scheduler now
I am called by MethodInvokingJobDetailFactoryBean using SimpleTriggerFactoryBean
I am called by Quartz jobBean using CronTriggerFactoryBean
I am called by MethodInvokingJobDetailFactoryBean using SimpleTriggerFactoryBean
I am called by MethodInvokingJobDetailFactoryBean using SimpleTriggerFactoryBean
I am called by Quartz jobBean using CronTriggerFactoryBean
I am called by MethodInvokingJobDetailFactoryBean using SimpleTriggerFactoryBean
I am called by MethodInvokingJobDetailFactoryBean using SimpleTriggerFactoryBean
I am called by MethodInvokingJobDetailFactoryBean using SimpleTriggerFactoryBean
I am called by Quartz jobBean using CronTriggerFactoryBean
I am called by MethodInvokingJobDetailFactoryBean using SimpleTriggerFactoryBean

Spring 4 + Quartz 2.2.1 Scheduler Integration Example的更多相关文章

  1. Spring 3 + Quartz 1.8.6 Scheduler Example--reference

    In this tutorial, we will show you how to integrate Spring with Quartz scheduler framework. Spring c ...

  2. spring结合quartz的定时的2种方式

    1. Spring 的org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean类,使用此方法使开发人员对Quar ...

  3. Spring对Quartz的封装实现简单需注意事项

    前段时间在项目中一直使用正常的Quartz突然出现了任务漏跑的情况,由于我以前看过Quartz的内部实现,凭借记忆我觉得是由于Quartz的线程池的使用出现问题导致了故障的发生.为了搞清问题的真相,我 ...

  4. Spring整合Quartz实现持久化、动态设定时间

    一.spring整合 网上一搜有很多整合的方式,这里我采用了其中的一种(暂时还没有对其他的方法研究过). 对于spring的整合其中的任务,spring提供了几个类.接口(这些类都实现了Job接口): ...

  5. spring整合quartz并持久化

    spring整合quartz有两种方式: 一.常见是使用配置文件,将定时任务保存到内存中 简单示例: <!-- 短信催还提醒任务调度 --> <bean id="overd ...

  6. Spring整合Quartz实现动态定时器

    一.版本说明 spring3.1以下的版本必须使用quartz1.x系列,3.1以上的版本才支持quartz 2.x,不然会出错. 原因:spring对于quartz的支持实现,org.springf ...

  7. Spring整合Quartz

    目录[-] 一.Spring创建JobDetail的两种方式 二.整合方式一示例步骤 1.将spring核心jar包.quartz.jar和Spring-context-support.jar导入类路 ...

  8. Quartz学习——Spring和Quartz集成详解(三)

    Spring是一个很优秀的框架,它无缝的集成了Quartz,简单方便的让企业级应用更好的使用Quartz进行任务的调度.下面就对Spring集成Quartz进行简单的介绍和示例讲解!和上一节 Quar ...

  9. Spring 整合 Quartz 实现动态定时任务

    复制自:https://www.2cto.com/kf/201605/504659.html 最近项目中需要用到定时任务的功能,虽然Spring 也自带了一个轻量级的定时任务实现,但感觉不够灵活,功能 ...

随机推荐

  1. TFS 2015 敏捷开发实践 – 看板的使用

    看板在现代应用开发过程中使用非常广泛,不管是使用传统的瀑布式开发还是敏捷开发,都可以使用看板管理.因为看板拥有简单的管理方法,直观的显示方式,所以很多软件开发团队选择使用看板进行软件开发管理.本文不在 ...

  2. Ubuntu下开启php调试模式,显示报错信息

    在Ubuntu下php的缺省设置是不显示错误信息的,如果程序出错会显示“无法处理此请求的错误提示”,这在开发环境下非常不方便. 其实我们只要编辑下apache的配置文件就好 1.我的apache 配置 ...

  3. μCos-ii学习笔记1_概述

    一.μCos-ii _概述 网上关于μCosii的文章多不胜数,本人学习的过程中也参考了很多人的理解和想法,看的是卢有亮老师的<嵌入式实时操作系统-μC/OS原理与实践>(第2版),同时也 ...

  4. hibernate5.2需要的最少jar文件

    hibernate5.2需要的最少jar文件: required文件夹中的所有jar文件 + mysql-connector-java-bin.jar.

  5. PHP 数组浅析

    PHP的数组具有如下特点:1.数组初始化时无需指定长度:2.数组中的元素无需相同类型:3.数组的长度可变4.可使用var_dump(参数)或者print_r(  参数) 函数查看数组变量.5.数组内的 ...

  6. 数据库 oracle数据库基本知识

    sqlplus登录 普通用户登录 c:\>sqlplus 请输入用户名:scott 请输入口令: sqlplus scott/ quit退出 管理员登录 sqlplus /nolog 连接数据库 ...

  7. MVC5在Mono上的各种坑

    买了Macbook后,各种事情的纠缠,都没好好地用过OSX系统. 果断的装上了xcode和mono,还有monodevelop. 然后把项目移植到mono上运行,各种问题. 然后第一个问题来了 权限不 ...

  8. Git 进阶指南(git ssh keys / reset / rebase / alias / tag / submodule )

    在掌握了基础的 Git 使用 之后,可能会遇到一些常见的问题.以下是猫哥筛选总结的部分常见问题,分享给各位朋友,掌握了这些问题的中的要点之后,git 进阶也就完成了,它包含以下部分: 如何修改 ori ...

  9. EasyPR--开发详解(8)文字定位

    今天我们来介绍车牌定位中的一种新方法--文字定位方法(MSER),包括其主要设计思想与实现.接着我们会介绍一下EasyPR v1.5-beta版本中带来的几项改动. 一. 文字定位法 在EasyPR前 ...

  10. 对于前端,「微信小程序」其实不美好

    微信小程序开放公测了,9月底我曾经写过一篇 「微信小程序」来了,其中最后一句:"谢天谢地,我居然还是个前端". 这种火爆的新事物总是令人激动,感谢这个时代. 但是,当我真作为开发者 ...