一、背景
SSM项目中要用到定时器,初期使用Timer,后来用spring 的schedule,都比较简单,所以功能比较单一而且他们不能动态的配置时间。后来就研究quartz,准备整合到项目中。Quartz 是一个完全由 Java 编写的开源作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。
二、quartz的官网下载压缩包
最好下载稳定版,我这里下载的是2.3.0,。
三、建立数据库,导入sql脚本
sql脚本的位置:quartz-2.3.0-distribution\quartz-2.3.0-SNAPSHOT\src\org\quartz\impl\jdbcjobstore\tables_mysql_innodb.sql(我项目中使用的mysql),这里要注意,不同类型的数据库要用不同的数据库脚本;
四、Maven中导入依赖
这里quartz的版本必须与数据库脚本的版本一致不然会报错。因为quartz的每个版本数据库改动挺大的,假如这里配置的2.3.0,而你用2.1.7的sql脚本,肯定会出错。所以要一一匹配。
org.quartz-scheduler quartz 2.3.0 org.quartz-scheduler quartz-jobs 2.3.0
五、配置文件
quartz的持久化有两种,一种是RAM,一种是JDBC。
RAMJobStore是使用最简单的JobStore,它也是性能最高的(在CPU时间方面)。RAMJobStore以其明显的方式获取其名称:它将其所有数据保存在RAM中。这就是为什么它是闪电般快的,也是为什么这么简单的配置。缺点是当您的应用程序结束(或崩溃)时,所有调度信息都将丢失 - 这意味着RAMJobStore无法履行作业和triggers上的“非易失性”设置。对于某些应用程序,这是可以接受的 - 甚至是所需的行为,但对于其他应用程序,这可能是灾难性的。
JDBCJobStore也被恰当地命名 - 它通过JDBC将其所有数据保存在数据库中。因此,配置比RAMJobStore要复杂一点,而且也不是那么快。但是,性能下降并不是很糟糕,特别是如果您在主键上构建具有索引的数据库表。在相当现代的一套具有体面的LAN(在调度程序和数据库之间)的机器上,检索和更新触发triggers的时间通常将小于10毫秒。
本次整合采用的是JDBCStore。如果你采用RAMStore,你只需要将org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX注释掉,把Configure Datasources标签中的内容注释掉。
# Default Properties file for use by StdSchedulerFactory# to create a Quartz Scheduler Instance, if a different# properties file is not explicitly specified.##============================================================================# Configure Main Scheduler Properties#============================================================================org.quartz.scheduler.instanceName: quartzSchedulerorg.quartz.scheduler.instanceId = AUTOorg.quartz.scheduler.rmi.export: falseorg.quartz.scheduler.rmi.proxy: falseorg.quartz.scheduler.wrapJobExecutionInUserTransaction: false#============================================================================# Configure ThreadPool#============================================================================org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPoolorg.quartz.threadPool.threadCount: 2org.quartz.threadPool.threadPriority: 5org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: trueorg.quartz.jobStore.misfireThreshold: 60000#============================================================================# Configure JobStore#============================================================================#default config#org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore#持久化配置org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTXorg.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegateorg.quartz.jobStore.useProperties:true#============================================================================#havent cluster spring#============================================================================org.quartz.jobStore.isClustered = false#数据库表前缀org.quartz.jobStore.tablePrefix:qrtz_#============================================================================# Configure Datasources,如果在spring的配置文件中,指定dataSource,那么就是用的spring中已经配置好的数据源,即被覆盖。如果没有指定dataSource,则使用的是此处配置的数据库参数#============================================================================org.quartz.jobStore.dataSource:qzDSorg.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driverorg.quartz.dataSource.qzDS.URL:jdbc:mysql://localhost:3306/magicmedecgorg.quartz.dataSource.qzDS.user:rootorg.quartz.dataSource.qzDS.password:root
六、spring与quartz的整合配置
七、定义Job类
这里的@Setter是生成类的属性的setter方法,这个注解不是quartz的,而是lombok的。@sertter = 属性的setter方法。
@Setterpublic class RemindUserJob implements Job { private String appuserId; private String orderSn; private static int count = 0; @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap(); System.out.println("我执行了,时间是" + System.currentTimeMillis() + ",count = " + count + ",appuserId = " + appuserId + ",orderSn=" + orderSn); count++; }}
八、创建任务
@RequestMapping("test04") @ResponseBody public void test04() throws Exception { // 创建scheduler Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // 创建JobDetail JobDetail jobDetail = newJob(RemindUserJob.class) .withIdentity("job1", "group1") .usingJobData("appuserId", "asdfghjkl") .usingJobData("orderSn", "0as8fg") .build(); // 指定时间触发,每隔2s执行一次,重复20次 Trigger trigger2 = newTrigger() .withIdentity("trigger2", "group1") .startAt(new Date()) .withSchedule(simpleSchedule() .withIntervalInSeconds(2) .withRepeatCount(20)) .build(); scheduler.scheduleJob(jobDetail,trigger2); scheduler.start(); }
九、运行效果
[2019-03-25 15:11:08,149] [org.quartz.impl.StdSchedulerFactory] : Quartz scheduler 'quartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'[2019-03-25 15:11:08,150] [org.quartz.impl.StdSchedulerFactory] : Quartz scheduler version: 2.3.0[2019-03-25 15:11:08,255] [com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource] : Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, dataSourceName -> 1hge15ka11duunroghgkbm|aa25642, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> 1hge15ka11duunroghgkbm|aa25642, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/magicmedecg, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 10, maxStatements -> 0, maxStatementsPerConnection -> 120, minPoolSize -> 1, numHelperThreads -> 3, preferredTestQuery -> null, privilegeSpawnedThreads -> false, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ][2019-03-25 15:11:08,525] [org.quartz.impl.jdbcjobstore.JobStoreTX] : Freed 0 triggers from 'acquired' / 'blocked' state.[2019-03-25 15:11:08,530] [org.quartz.impl.jdbcjobstore.JobStoreTX] : Recovering 0 jobs that were in-progress at the time of the last shut-down.[2019-03-25 15:11:08,530] [org.quartz.impl.jdbcjobstore.JobStoreTX] : Recovery complete.[2019-03-25 15:11:08,532] [org.quartz.impl.jdbcjobstore.JobStoreTX] : Removed 0 'complete' triggers.[2019-03-25 15:11:08,534] [org.quartz.impl.jdbcjobstore.JobStoreTX] : Removed 0 stale fired job entries.[2019-03-25 15:11:08,535] [org.quartz.core.QuartzScheduler] : Scheduler quartzScheduler_$_NON_CLUSTERED started.我执行了,时间是1553497868902,count = 0,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497870183,count = 1,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497872178,count = 2,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497874183,count = 3,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497876179,count = 4,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497878177,count = 5,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497880178,count = 6,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497882180,count = 7,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497884183,count = 8,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497886184,count = 9,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497888176,count = 10,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497890175,count = 11,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497892177,count = 12,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497894178,count = 13,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497896176,count = 14,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497898190,count = 15,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497900381,count = 16,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497902176,count = 17,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497904205,count = 18,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497906175,count = 19,appuserId = asdfghjkl,orderSn=0as8fg我执行了,时间是1553497908177,count = 20,appuserId = asdfghjkl,orderSn=0as8fg
注:整合过程中可能遇到的异常: