RAMJobStore
with Quartz you don't really need Quartz at all. Obviously this storage backend is transient and all your pending jobs and triggers are lost between restarts. If you are fine with that, much simpler and more lightweight solutions are available, including ScheduledExecutorService
built into JDK and @Scheduled(cron="*/5 * * * * MON-FRI")
in Spring. Can you justify using extra 0,5MiB JAR in this scenario? This changes dramatically when you need clustering, fail-over, load-balancing and few other buzz-words. There are several use-cases for that:
- single server cannot handle required number of concurrent, long running jobs and the executions need to be split into several machines - but each task must be executed exactly ones
- we cannot afford to run jobs too late - if one server is down, another should run the job on time
- ...or less strictly - the job needs to run eventually - even if the one and only server was down for maintenance, delayed jobs need to be run as soon as possible after restart
So if you think you need to schedule jobs and have some of the requirements above, keep reading. I will show you how to configure Quartz with Spring and fully integrate them. First of all we need a
DataSource
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import org.apache.commons.dbcp.BasicDataSource
import com.googlecode.flyway.core.Flyway
import org.jdbcdslog.DataSourceProxy
import org.springframework.jdbc.datasource.{DataSourceTransactionManager, LazyConnectionDataSourceProxy}
import org.h 2 .Driver
@ Configuration @ EnableTransactionManagement class Persistence {
@ Bean def transactionManager() = new DataSourceTransactionManager(dataSource())
@ Bean @ Primary def dataSource() = {
val proxy = new DataSourceProxy()
proxy.setTargetDSDirect(dbcpDataSource()) new LazyConnectionDataSourceProxy(proxy)
} @ Bean(destroyMethod = "close" )
def dbcpDataSource() = {
val dataSource = new BasicDataSource
dataSource.setDriverClassName(classOf[Driver].getName) dataSource.setUrl( "jdbc:h2:mem:quartz-demo;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MVCC=TRUE" ) dataSource.setUsername( "sa" ) dataSource.setPassword( "" ) dataSource.setMaxActive( 20 ) dataSource.setMaxIdle( 20 ) dataSource.setMaxWait( 10000 ) dataSource.setInitialSize( 5 ) dataSource.setValidationQuery( "SELECT 1" ) dataSource } } |
1
2
3
4
5
6
|
@ Bean(initMethod = "migrate" )
def flyway() = {
val fly = new Flyway()
fly.setDataSource(dataSource()) fly } |
Let's move on to Quartz:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
@ Configuration class Scheduling {
@ Resource val persistence : Persistence = null
@ Bean @ DependsOn(Array( "flyway" )) def schedulerFactory() = {
val schedulerFactoryBean = new SchedulerFactoryBean()
schedulerFactoryBean.setDataSource(persistence.dataSource()) schedulerFactoryBean.setTransactionManager(persistence.transactionManager()) schedulerFactoryBean.setConfigLocation( new ClassPathResource( "quartz.properties" ))
schedulerFactoryBean.setJobFactory(jobFactory()) schedulerFactoryBean.setApplicationContextSchedulerContextKey( "applicationContext" ) schedulerFactoryBean.setSchedulerContextAsMap(Map().asJava) schedulerFactoryBean.setWaitForJobsToCompleteOnShutdown( true ) schedulerFactoryBean } @ Bean def jobFactory() = new SpringBeanJobFactory
} |
@Configuration
annotated classes into another such class for convenience. Except that - nothing fancy. Note that we need @DependsOn(Array("flyway"))
on Quartz scheduler factory - otherwise the scheduler might start before Flyway fired the migration script with Quartz database tables causing unpleasant errors on startup. The essential bits are SpringBeanJobFactory
and schedulerContextAsMap
. The special factory makes Spring responsible for creating Job
instances. Unfortunately this factory is quite limited which we will see shortly in the following example. First we need a Spring bean and a Quartz job:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@ Service class Printer extends Logging {
def print(msg : String) {
logger.info(msg) } } class PrintMessageJob extends Job with Logging {
@ BeanProperty var printer : Printer = _
@ BeanProperty var msg = ""
def execute(context : JobExecutionContext) {
printer print msg } } |
@BeanProperty
instead of @Autowired
or @Resource
. Turns out that Job
is not really a Spring bean, even though Spring creates an instance of it. Instead Spring discovers required dependencies using available setters. So where does the msg
string come from? Keep going:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
val trigger = newTrigger().
withIdentity( "Every-few-seconds" , "Demo" ). withSchedule( simpleSchedule(). withIntervalInSeconds( 4 ). repeatForever() ). build() val job = newJob(classOf[PrintMessageJob]).
withIdentity( "Print-message" , "Demo" ). usingJobData( "msg" , "Hello, world!" ). build() scheduler.scheduleJob(job, trigger) |
"Hello, world!"
parameter to the job. This parameter is stored in so called JobData
in the database per job or per trigger. It will be provided to the job when it is executed. This way you can parametrize your jobs. However when executed our job throws NullPointerException
... Apparently printer
reference was not set and silently ignored. Turns out Spring won't simply look through all the beans available in the ApplicationContext
. The SpringBeanJobFactory
only looks into Jobs'
and Triggers'
JobData
and into so called scheduler context (already mentioned). If you want to inject any Spring bean into Job
you must explicitly place a reference to that bean in schedulerContext
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@ Configuration class Scheduling {
@ Resource val printer : Printer = null
@ Bean def schedulerFactory() = {
val schedulerFactoryBean = new SchedulerFactoryBean()
//... schedulerFactoryBean.setSchedulerContextAsMap(schedulerContextMap().asJava) //... schedulerFactoryBean } def schedulerContextMap() =
Map( "printer" -> printer
) } |
schedulerContextMap
. Even worse, if you forget about it, Quartz will silently log NPE at runtime. In the future we will write more robust job factory. But for starters we have a working Spring + Quartz application ready for further experiments, sources as always available under my GitHub account. You might ask yourself way can't we simply use MethodInvokingJobDetailFactoryBean? Well, first of all because it does not work with persistent job stores. Secondly - because it is unable to pass
JobData
to Job
- so we can no longer distinguish between different job runs. For instance our job printing message would have to always print the same message hard-coded in the class. BTW if anyone asks you: How many classes does a Java enterprise developer need to print “Hello world!" you can proudly reply: 4 classes, 30 JARs taking 20 MiB of space and a relational database with 10+ tables. Seriously, this is an output of our article here...
相关推荐
赠送jar包:quartz-2.3.2.jar; 赠送原API文档:quartz-2.3.2-javadoc.jar; 赠送源代码:quartz-2.3.2-sources.jar; 赠送Maven依赖信息文件:quartz-2.3.2.pom; 包含翻译后的API文档:quartz-2.3.2-javadoc-API...
赠送jar包:quartz-2.3.0.jar; 赠送原API文档:quartz-2.3.0-javadoc.jar; 赠送源代码:quartz-2.3.0-sources.jar; 赠送Maven依赖信息文件:quartz-2.3.0.pom; 包含翻译后的API文档:quartz-2.3.0-javadoc-API...
文件里面包括 1:Quartz开发指南.pdf 2:Quartz从入门到进阶.pdf 3:QuartzBeginnerExample一个附带的工程例子 4:quartz-1.6.1.zip Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它...
网上能找到的Quartz Web管理的资料都是使用的一个国外人写的Quartz WebApp的东东,功能也很全面。但是作为自己的应用其实用不了那么多功能,一般我们只要可以定义一个job,指定一个Cron表达式完成工作即可,附带的...
quartz quartz-1.8.6 dbTables quartz动态任务调度需要的数据库脚本。
Quartz.NET框架的核心是调度器。调度器负责管理Quartz.NET应用运行时环境。Quartz不仅仅是线程和线程管理。为确保可伸缩性,Quartz.NET采用了基于多线程的架构。启动时,框架初始化一套worker线程,这套线程被调度器...
该压缩包内包含两个quartz的jar包, 分别是quartz-1.6.0.jar和quartz-all-1.6.0.jar
quartz-2.2.3版本的quartz初始化sql语句
Quartz是一个开源的作业调度框架,它完全由Java写成,并设计用于J2SE和J2EE应用中。它提供了巨大的灵 活性而不牺牲简单性。你能够用它来为执行一个作业而创建简单的或复杂的调度 What's New In Quartz Scheduler ...
Quartz原理及实例,spring4.x+Quartz.2.2.1结合的开发,静态和动态实例
Quartz框架的核心是调度器。调度器负责管理Quartz应用运行时环境。调度器不是靠自己做所有的工作,而是依赖框架内一些非常重要的部件。 Quartz不仅仅是线程和线程管理。为确保可伸缩性,Quartz采用了基于多线程的...
赠送jar包:quartz-2.3.0.jar; 赠送原API文档:quartz-2.3.0-javadoc.jar; 赠送源代码:quartz-2.3.0-sources.jar; 赠送Maven依赖信息文件:quartz-2.3.0.pom; 包含翻译后的API文档:quartz-2.3.0-javadoc-API...
赠送jar包:quartz-1.6.1.jar; 赠送原API文档:quartz-1.6.1-javadoc.jar; 包含翻译后的API文档:quartz-1.6.1-javadoc-API文档-中文(简体)版.zip 对应Maven信息:groupId:org.opensymphony.quartz,...
Quartz是一个功能丰富的开源作业调度库,几乎可以集成在任何Java应用程序中 - 从最小的独立应用程序到最大的电子商务系统。Quartz可用于创建简单或复杂的计划,以执行数十,数百甚至数万个作业; 将任务定义为标准...
Quartz框架的核心是调度器。调度器负责管理Quartz应用运行时环境。调度器不是靠自己做所有的工作,而是依赖框架内一些非常重要的部件。 Quartz不仅仅是线程和线程管理。为确保可伸缩性,Quartz采用了基于多线程的...
Quartz框架的核心是调度器。调度器负责管理Quartz应用运行时环境。调度器不是靠自己做所有的工作,而是依赖框架内一些非常重要的部件。 Quartz不仅仅是线程和线程管理。为确保可伸缩性,Quartz采用了基于多线程的...
前言:8月份翻译了Quartz.NET的官方课程:开源的作业调度框架 - Quartz.NET, 有的朋友抱怨难用,确实,目前Qiartz.NET的最新版本还是0.6,还存在很多bug和不完善的地方。本文使用一系列代码示例介绍 Quartz.NET API...
深入解读Quartz的原理,定时任务框架是web开发过程中使用很多的框架之一
Quartz is a richly featured, open source job scheduling library that can be integrated within virtually any Java application - from the smallest stand-alone application to the largest e-commerce ...
Quartz定时任务