Quartz与SpringMVC的整合
简介
Quartz是一个完全由java编写的开源作业调度框架,为在Java应用程序中进行作业调度提供了简单却强大的机制。Quartz允许开发人员根据时间间隔来调度作业。它实现了作业和触发器的多对多的关系,还能把多个作业与不同的触发器关联。这篇文章介绍了Quartz与SSM框架的整合,包括了持久化的方法和对于任务的一些简单操作。本文包括一个简单的由vuejs和ElementUI开发的前端任务管理页面,对于vuejs和ElementUI的用法,在我的另一篇文章中进行了详细的介绍,并且有完整的代码可供参考,这里不再赘述。
正文
Quartz的引入
在pom.xml中加入如下代码:
org.quartz-scheduler quartz 2.2.1 org.quartz-scheduler quartz-jobs 2.2.1
在web.xml中,加入如下代码:
quartz:config-file scan-quartz.properties quartz:shutdown-on-unload true quartz:wait-on-shutdown false quartz:start-scheduler-on-load true org.quartz.ee.servlet.QuartzInitializerListener
scan-quartz.properties是quartz的配置文件,我们需要在resouces目录下加入新建一个名字为scan-quartz.properties的文件,然后在里面加入
# 固定前缀org.quartz# 主要分为scheduler、threadPool、jobStore、plugin等部分##org.quartz.scheduler.instanceName = DefaultQuartzSchedulerorg.quartz.scheduler.rmi.export = falseorg.quartz.scheduler.rmi.proxy = falseorg.quartz.scheduler.wrapJobExecutionInUserTransaction = false# 实例化ThreadPool时,使用的线程类为SimpleThreadPoolorg.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool# threadCount和threadPriority将以setter的形式注入ThreadPool实例# 并发个数org.quartz.threadPool.threadCount = 5# 优先级org.quartz.threadPool.threadPriority = 5org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = trueorg.quartz.jobStore.misfireThreshold = 5000# 默认存储在内存中org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
上面的最后一句话的作用是把任务内容存储在内存中。我们的程序是要做持久化任务,所以把上面的最后一句话注释掉,然后在下面加上
#持久化org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTXorg.quartz.jobStore.tablePrefix = QRTZ_org.quartz.jobStore.dataSource = qzDSorg.quartz.dataSource.qzDS.driver = com.mysql.jdbc.Driverorg.quartz.dataSource.qzDS.URL = jdbc:mysql://190.0.1.88:3306/hello_test?useUnicode=true&characterEncoding=UTF-8org.quartz.dataSource.qzDS.user = rootorg.quartz.dataSource.qzDS.password = rootorg.quartz.dataSource.qzDS.maxConnections = 10
上面代码主要是做了一些数据库的连接配置,如果大家用过mybatis,这些应该都能看懂。不过,事先要在数据库里创建一些表。具体的做法是打开数据库客户端,连接到某个数据库,然后新建一个查询。如果你用到的是mysql数据库,那么执行以下代码:
## Quartz seems to work best with the driver mm.mysql-2.0.7-bin.jar## PLEASE consider using mysql with innodb tables to avoid locking issues## In your Quartz properties file, you'll need to set # org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate#DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS;DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS;DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE;DROP TABLE IF EXISTS QRTZ_LOCKS;DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS;DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS;DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS;DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS;DROP TABLE IF EXISTS QRTZ_TRIGGERS;DROP TABLE IF EXISTS QRTZ_JOB_DETAILS;DROP TABLE IF EXISTS QRTZ_CALENDARS;CREATE TABLE QRTZ_JOB_DETAILS ( SCHED_NAME VARCHAR(120) NOT NULL, JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, DESCRIPTION VARCHAR(250) NULL, JOB_CLASS_NAME VARCHAR(250) NOT NULL, IS_DURABLE VARCHAR(1) NOT NULL, IS_NONCONCURRENT VARCHAR(1) NOT NULL, IS_UPDATE_DATA VARCHAR(1) NOT NULL, REQUESTS_RECOVERY VARCHAR(1) NOT NULL, JOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP));CREATE TABLE QRTZ_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, JOB_NAME VARCHAR(200) NOT NULL, JOB_GROUP VARCHAR(200) NOT NULL, DESCRIPTION VARCHAR(250) NULL, NEXT_FIRE_TIME BIGINT(13) NULL, PREV_FIRE_TIME BIGINT(13) NULL, PRIORITY INTEGER NULL, TRIGGER_STATE VARCHAR(16) NOT NULL, TRIGGER_TYPE VARCHAR(8) NOT NULL, START_TIME BIGINT(13) NOT NULL, END_TIME BIGINT(13) NULL, CALENDAR_NAME VARCHAR(200) NULL, MISFIRE_INSTR SMALLINT(2) NULL, JOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP) REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP));CREATE TABLE QRTZ_SIMPLE_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, REPEAT_COUNT BIGINT(7) NOT NULL, REPEAT_INTERVAL BIGINT(12) NOT NULL, TIMES_TRIGGERED BIGINT(10) NOT NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP));CREATE TABLE QRTZ_CRON_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, CRON_EXPRESSION VARCHAR(200) NOT NULL, TIME_ZONE_ID VARCHAR(80), PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP));CREATE TABLE QRTZ_SIMPROP_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, STR_PROP_1 VARCHAR(512) NULL, STR_PROP_2 VARCHAR(512) NULL, STR_PROP_3 VARCHAR(512) NULL, INT_PROP_1 INT NULL, INT_PROP_2 INT NULL, LONG_PROP_1 BIGINT NULL, LONG_PROP_2 BIGINT NULL, DEC_PROP_1 NUMERIC(13,4) NULL, DEC_PROP_2 NUMERIC(13,4) NULL, BOOL_PROP_1 VARCHAR(1) NULL, BOOL_PROP_2 VARCHAR(1) NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP));CREATE TABLE QRTZ_BLOB_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, BLOB_DATA BLOB NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP));CREATE TABLE QRTZ_CALENDARS ( SCHED_NAME VARCHAR(120) NOT NULL, CALENDAR_NAME VARCHAR(200) NOT NULL, CALENDAR BLOB NOT NULL, PRIMARY KEY (SCHED_NAME,CALENDAR_NAME));CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS ( SCHED_NAME VARCHAR(120) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP));CREATE TABLE QRTZ_FIRED_TRIGGERS ( SCHED_NAME VARCHAR(120) NOT NULL, ENTRY_ID VARCHAR(95) NOT NULL, TRIGGER_NAME VARCHAR(200) NOT NULL, TRIGGER_GROUP VARCHAR(200) NOT NULL, INSTANCE_NAME VARCHAR(200) NOT NULL, FIRED_TIME BIGINT(13) NOT NULL, SCHED_TIME BIGINT(13) NOT NULL, PRIORITY INTEGER NOT NULL, STATE VARCHAR(16) NOT NULL, JOB_NAME VARCHAR(200) NULL, JOB_GROUP VARCHAR(200) NULL, IS_NONCONCURRENT VARCHAR(1) NULL, REQUESTS_RECOVERY VARCHAR(1) NULL, PRIMARY KEY (SCHED_NAME,ENTRY_ID));CREATE TABLE QRTZ_SCHEDULER_STATE ( SCHED_NAME VARCHAR(120) NOT NULL, INSTANCE_NAME VARCHAR(200) NOT NULL, LAST_CHECKIN_TIME BIGINT(13) NOT NULL, CHECKIN_INTERVAL BIGINT(13) NOT NULL, PRIMARY KEY (SCHED_NAME,INSTANCE_NAME));CREATE TABLE QRTZ_LOCKS ( SCHED_NAME VARCHAR(120) NOT NULL, LOCK_NAME VARCHAR(40) NOT NULL, PRIMARY KEY (SCHED_NAME,LOCK_NAME));commit;
如果是其他的数据库,可以从下载完整的文档,然后在docs目录下的dbTables文件夹里找到对应的创建表的方法。
后台代码
先创建两个任务类HelloJob和NewJob
import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class HelloJob implements Job { private static Logger _log = LoggerFactory.getLogger(HelloJob.class); public HelloJob() { } public void execute(JobExecutionContext context) throws JobExecutionException { _log.error("Hello Job执行时间: " + new Date()); } }
import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class NewJob implements Job { private static Logger _log = LoggerFactory.getLogger(HelloJob.class); public NewJob() { } public void execute(JobExecutionContext context) throws JobExecutionException { _log.error("New Job执行时间: " + new Date()); } }
这两个任务类的执行都是简单的打印执行时间。
接下来是Controller,首先是添加任务@ResponseBody @RequestMapping(value="/addjob", method = RequestMethod.POST) public void addjob(@RequestParam(value="jobClassName")String jobClassName) throws Exception { setJob(jobClassName); } public static void setJob(String jobClassName) throws Exception { // 通过SchedulerFactory获取一个调度器实例 SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); // 启动调度器 sched.start(); switch (jobClassName) { case "HelloJob": JobDetail job = newJob(HelloJob.class).withIdentity("HelloJob", "group1").build(); Trigger trigger = newTrigger().withIdentity("HelloJob", "group1").startNow().withSchedule(simpleSchedule() .withIntervalInSeconds(10) .repeatForever()).build(); sched.scheduleJob(job, trigger); break; case "NewJob": JobDetail job2 = newJob(NewJob.class).withIdentity("NewJob", "group1").build(); Trigger trigger2 = newTrigger().withIdentity("NewJob", "group1").startNow().withSchedule(simpleSchedule() .withIntervalInSeconds(10) .repeatForever()).build(); sched.scheduleJob(job2, trigger2); break; default: break; } }
从前端接收一个名称参数,然后根据这个名称创建对应的任务实例。每个任务都有个触发器,这里两个任务都设置为每10秒钟运行一次,永久循环。每个任务实例都需要一个名称和组,对于两个任务实例来说,名称和组不能全部相同,因为它们在寻找任务实例中起到key的作用。
接下来是暂停任务。
@ResponseBody @RequestMapping(value="/pausejob", method = RequestMethod.POST) public void pausejob(@RequestParam(value="jobClassName")String jobClassName) throws Exception { jobPause(jobClassName); } public static void jobPause(String jobClassName) throws Exception { // 通过SchedulerFactory获取一个调度器实例 SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); switch (jobClassName) { case "HelloJob": sched.pauseJob(JobKey.jobKey("HelloJob", "group1")); break; case "NewJob": sched.pauseJob(JobKey.jobKey("NewJob", "group1")); break; default: break; } }
可以看到上文通过jobkey找到了这个任务的实例,然后进行暂停操作。
接下来恢复。@ResponseBody @RequestMapping(value="/resumejob", method = RequestMethod.POST) public void resumejob(@RequestParam(value="jobClassName")String jobClassName) throws Exception { jobresume(jobClassName); } public static void jobresume(String jobClassName) throws Exception { // 通过SchedulerFactory获取一个调度器实例 SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); if(sched != null){ switch (jobClassName) { case "HelloJob": sched.resumeJob(JobKey.jobKey("HelloJob", "group1")); break; case "NewJob": sched.resumeJob(JobKey.jobKey("NewJob", "group1")); break; default: break; } } }
然后是删除操作。
@ResponseBody @RequestMapping(value="/deletejob", method = RequestMethod.POST) public void deletejob(@RequestParam(value="jobClassName")String jobClassName) throws Exception { jobdelete(jobClassName); } public static void jobdelete(String jobClassName) throws Exception { // 通过SchedulerFactory获取一个调度器实例 SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); switch (jobClassName) { case "HelloJob": sched.pauseTrigger(TriggerKey.triggerKey("HelloJob", "group1")); sched.unscheduleJob(TriggerKey.triggerKey("HelloJob", "group1")); sched.deleteJob(JobKey.jobKey("HelloJob", "group1")); break; case "NewJob": sched.pauseTrigger(TriggerKey.triggerKey("NewJob", "group1")); sched.unscheduleJob(TriggerKey.triggerKey("NewJob", "group1")); sched.deleteJob(JobKey.jobKey("NewJob", "group1")); break; default: break; } }
删除操作前应该暂停该任务的触发器,并且停止该任务的执行。
最后是查询,这里用到了pageHelper插件,具体的也是写在了中。
@ResponseBody @RequestMapping(value="/queryjob") public Mapqueryjob(@RequestParam(value="pageNum")Integer pageNum, @RequestParam(value="pageSize")Integer pageSize) { Page jobAndTrigger = iJobAndTriggerService.getJobAndTriggerDetails(pageNum, pageSize); Map map = new HashMap (); map.put("JobAndTrigger", jobAndTrigger); map.put("number", jobAndTrigger.getTotal()); return map; }
这里主要的作用是将数据库里存储的关于任务和触发器的部分信息查询出来在前端显示。附上mybatis中的sql代码
最后显示的效果如图所示
[com.hdnav.core.HelloJob] - New Job执行时间: Thu Apr 20 18:01:47 CST 2017[com.hdnav.core.HelloJob] - Hello Job执行时间: Thu Apr 20 18:01:57 CST 2017[com.hdnav.core.HelloJob] - New Job执行时间: Thu Apr 20 18:01:57 CST 2017[com.hdnav.core.HelloJob] - Hello Job执行时间: Thu Apr 20 18:02:07 CST 2017[com.hdnav.core.HelloJob] - New Job执行时间: Thu Apr 20 18:02:07 CST 2017[com.hdnav.core.HelloJob] - Hello Job执行时间: Thu Apr 20 18:02:17 CST 2017[com.hdnav.core.HelloJob] - New Job执行时间: Thu Apr 20 18:02:17 CST 2017[com.hdnav.core.HelloJob] - Hello Job执行时间: Thu Apr 20 18:02:27 CST 2017[com.hdnav.core.HelloJob] - New Job执行时间: Thu Apr 20 18:02:27 CST 2017[com.hdnav.core.HelloJob] - Hello Job执行时间: Thu Apr 20 18:02:37 CST 2017
可以看到两个任务都是每隔10秒执行一次。
若点击暂停,则该任务暂停执行。点击恢复则会恢复执行。 若执行删除操作,则数据表内不再有该任务的数据,只有重新添加任务才会显示,不过所有的数据都会重置。[com.hdnav.core.HelloJob] - Hello Job执行时间: Thu Apr 20 18:08:07 CST 2017[com.hdnav.core.HelloJob] - New Job执行时间: Thu Apr 20 18:08:07 CST 2017[com.hdnav.core.HelloJob] - Hello Job执行时间: Thu Apr 20 18:08:17 CST 2017[com.hdnav.core.HelloJob] - New Job执行时间: Thu Apr 20 18:08:17 CST 2017[com.hdnav.core.dao.JobAndTriggerMapper.getJobAndTriggerDetails] - ==> Preparing: SELECT qrtz_job_details.JOB_NAME, qrtz_job_details.JOB_GROUP, qrtz_job_details.JOB_CLASS_NAME, qrtz_triggers.TRIGGER_NAME, qrtz_triggers.TRIGGER_GROUP, qrtz_simple_triggers.REPEAT_INTERVAL, qrtz_simple_triggers.TIMES_TRIGGERED FROM qrtz_job_details JOIN qrtz_triggers JOIN qrtz_simple_triggers ON qrtz_job_details.JOB_NAME = qrtz_triggers.JOB_NAME AND qrtz_triggers.TRIGGER_NAME = qrtz_simple_triggers.TRIGGER_NAME AND qrtz_triggers.TRIGGER_GROUP = qrtz_simple_triggers.TRIGGER_GROUP LIMIT 10 [com.hdnav.core.dao.JobAndTriggerMapper.getJobAndTriggerDetails] - ==> Parameters: [com.hdnav.core.dao.JobAndTriggerMapper.getJobAndTriggerDetails] - <== Total: 1[com.hdnav.core.HelloJob] - New Job执行时间: Thu Apr 20 18:08:27 CST 2017[com.hdnav.core.HelloJob] - New Job执行时间: Thu Apr 20 18:08:37 CST 2017[com.hdnav.core.HelloJob] - New Job执行时间: Thu Apr 20 18:08:47 CST 2017
可以看到当执行删除HelloJob操作之后,控制台不再有指令。此时数据表中该条数据也被删除。
前端代码
前端代码比较简单,这里不再做过多的解释。
QuartzDemo 查询 添加 暂停 恢复 删除
至此,一个简单的SSM框架与Quartz的整合工程便做好了。虽然是一个很简单的Demo,但是功能还算完整。对于人物的修改,后台的代码如下:
@ResponseBody @RequestMapping(value="/reschedulejob", method = RequestMethod.POST) public void rescheduleJob(@RequestParam(value="jobClassName")String jobClassName) throws Exception { jobreschedule(jobClassName); } public static void jobreschedule(String jobClassName) throws Exception { SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); TriggerKey triggerKey = TriggerKey.triggerKey(jobClassName, "group1"); Trigger newTrigger = scheduler.getTrigger(triggerKey); scheduler.rescheduleJob(triggerKey, newTrigger); scheduler.start(); }
当然这里的trigger可以重新自定义,达到修改任务的效果。不过和前端结合相对来说比较麻烦,所以没有写前端的代码。做这个Demo的主要目的是为了更直观的感受到Quartz的可持久化特性,并且与SpringMVC相结合,可以从一个简单的前端界面直接去操作和管理这些任务。
结束语
这个小小的Demo所展现出的功能只是quartz茫茫多的功能的冰山一角,不过quartz是一个比较简单易懂的开源框架,文档相对来说很全面,在企业级的web程序开发中也完全可以胜任。相对于这个小小的Demo,还有很多更强大的功能等待着我们去探索。