├── .gitignore ├── LICENSE ├── README.md └── demo ├── .gitattributes ├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ └── demo │ │ ├── DemoApplication.java │ │ ├── SchedulerConfig.java │ │ ├── controller │ │ └── JobController.java │ │ ├── dao │ │ └── JobAndTriggerMapper.java │ │ ├── entity │ │ └── JobAndTrigger.java │ │ ├── job │ │ ├── BaseJob.java │ │ ├── HelloJob.java │ │ ├── JobTest.java │ │ ├── MyJobOne.java │ │ └── NewJob.java │ │ ├── mapper │ │ └── JobMapper.xml │ │ └── service │ │ ├── IJobAndTriggerService.java │ │ └── impl │ │ └── JobAndTriggerImpl.java └── resources │ ├── application.yml │ ├── log4j.yml │ ├── quartz.properties │ └── static │ └── JobManager.html └── test └── java └── com └── example └── demo └── DemoApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 一、关于 Quartz 2 | ![Quartz logo](http://oeckzejn4.bkt.clouddn.com/20180623152976524823664.png) 3 | - Quartz 是一个完全由 Java 编写的开源作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制。 4 | - Quartz 可以与 J2EE 与 J2SE 应用程序相结合也可以单独使用。 5 | - Quartz 允许程序开发人员根据时间的间隔来调度作业。 6 | - Quartz 实现了作业和触发器的多对多的关系,还能把多个作业与不同的触发器关联。 7 | 8 | ## 二、Quartz 核心概念 9 | ![核心组件](http://oeckzejn4.bkt.clouddn.com/20180623152976577089638.png) 10 | - Scheduler:调度容器 11 | - Job:Job接口类,即被调度的任务 12 | - JobDetail :Job的描述类,job执行时的依据此对象的信息反射实例化出Job的具体执行对象。 13 | - Trigger:触发器,存放Job执行的时间策略。用于定义任务调度时间规则。 14 | - JobStore: 存储作业和调度期间的状态 15 | - Calendar:指定排除的时间点(如排除法定节假日) 16 | 17 | #### job 18 | Job 是一个接口,只有一个方法 `void execute(JobExecutionContext context)`,开发者实现接口来定义任务。`JobExecutionContext` 类提供了调度上下文的各种信息。Job 运行时的信息保存在 `JobDataMap` 实例中。例如: 19 | ```java 20 | public class HelloJob implements BaseJob { 21 | private static Logger _log = LoggerFactory.getLogger(HelloJob.class); 22 | public HelloJob() { } 23 | public void execute(JobExecutionContext context) throws JobExecutionException { 24 | _log.error("Hello Job执行时间: " + new Date()); 25 | } 26 | } 27 | ``` 28 | #### JobDetailImpl 类 / JobDetail 接口 29 | `JobDetailImpl`类实现了`JobDetail`接口,用来描述一个 job,定义了job所有属性及其 `get/set` 方法。下面是 job 内部的主要属性: 30 | ```table 31 | 属性名 | 说明 32 | class | 必须是job实现类(比如`JobImpl`),用来绑定一个具体`job` 33 | name | job 名称。如果未指定,会自动分配一个唯一名称。所有job都必须拥有一个唯一`name`,如果两个 job 的`name`重复,则只有最前面的 job 能被调度 34 | group | job 所属的组名 35 | description | job描述 36 | durability | 是否持久化。如果job设置为非持久,当没有活跃的`trigger`与之关联的时候,job 会自动从`scheduler`中删除。也就是说,非持久`job`的生命期是由`trigger`的存在与否决定的 37 | shouldRecover | 是否可恢复。如果 job 设置为可恢复,一旦 job 执行时`scheduler`发生`hard shutdown`(比如进程崩溃或关机),当`scheduler`重启后,该`job`会被重新执行 38 | jobDataMap | 除了上面常规属性外,用户可以把任意`kv`数据存入`jobDataMap`,实现 job 属性的无限制扩展,执行 job 时可以使用这些属性数据。此属性的类型是`JobDataMap`,实现了`Serializable`接口,可做跨平台的序列化传输 39 | ``` 40 | 41 | #### Trigger 42 | 是一个类,描述触发Job执行的时间触发规则。主要有 `SimpleTrigger` 和 `CronTrigger` 这两个子类。当仅需触发一次或者以固定时间间隔周期执行,`SimpleTrigger`是最适合的选择;而`CronTrigger`则可以通过`Cron`表达式定义出各种复杂时间规则的调度方案:如每早晨9:00执行,周一、周三、周五下午5:00执行等; 43 | 44 | 以下是 trigger 的属性: 45 | ```table 46 | 属性名 | 属性类型 | 说明 47 | name | 所有trigger通用 | trigger名称 48 | group | 所有trigger通用 | trigger所属的组名 49 | description | 所有trigger通用 | trigger描述 50 | calendarName | 所有trigger通用 | 日历名称,指定使用哪个Calendar类,经常用来从trigger的调度计划中排除某些时间段 51 | misfireInstruction | 所有trigger通用 | 错过job(未在指定时间执行的job)的处理策略,默认为MISFIRE\_INSTRUCTION\_SMART\_POLICY。详见这篇[blog](https://link.jianshu.com?t=http%3A%2F%2Fblog.csdn.net%2Fspbdev%2Farticle%2Fdetails%2F41679477)[^Quartz misfire](https://link.jianshu.com?t=%255BSpbDev%255D%28http%3A%2F%2Fmy.csdn.net%2FSpbDev%29%25EF%25BC%259A%255BQuartz%25E7%259A%2584misfire%255D%28http%3A%2F%2Fblog.csdn.net%2Fspbdev%2Farticle%2Fdetails%2F41679477%29) 52 | priority | 所有trigger通用 | 优先级,默认为5。当多个trigger同时触发job时,线程池可能不够用,此时根据优先级来决定谁先触发 53 | jobDataMap | 所有trigger通用 | 同job的jobDataMap。假如job和trigger的jobDataMap有同名key,通过getMergedJobDataMap()获取的jobDataMap,将以trigger的为准 54 | startTime | 所有trigger通用 | 触发开始时间,默认为当前时间。决定什么时间开始触发job 55 | endTime | 所有trigger通用 | 触发结束时间。决定什么时间停止触发job 56 | nextFireTime | SimpleTrigger私有 | 下一次触发job的时间 57 | previousFireTime | SimpleTrigger私有 | 上一次触发job的时间 58 | repeatCount | SimpleTrigger私有 | 需触发的总次数 59 | timesTriggered | SimpleTrigger私有 | 已经触发过的次数 60 | repeatInterval | SimpleTrigger私有 | 触发间隔时间 61 | ``` 62 | 63 | #### Calendar 64 | `org.quartz.Calendar`和 `java.util.Calendar`不同,它是一些日历特定时间点的集合(可以简单地将`org.quartz.Calendar`看作`java.util.Calendar`的集合——`java.util.Calendar`代表一个日历时间点,无特殊说明后面的`Calendar`即指`org.quartz.Calendar`)。一个Trigger可以和多个Calendar关联,以便排除或包含某些时间点。假设,我们安排每周星期一早上10:00执行任务,但是如果碰到法定的节日,任务则不执行,这时就需要在`Trigger`触发机制的基础上使用Calendar进行定点排除。 65 | 66 | #### Scheduler 67 | 调度器,代表一个**Quartz**的独立运行容器,好比一个『大管家』,这个大管家应该可以接受 `Job`, 然后按照各种`Trigger`去运行,**Trigger**和**JobDetail**可以注册到Scheduler中,两者在Scheduler中拥有各自的组及名称,组及名称是Scheduler查找定位容器中某一对象的依据,**Trigger的组及名称必须唯一,JobDetail的组和名称也必须唯一**(但可以和Trigger的组和名称相同,因为它们是不同类型的)。Scheduler定义了多个接口方法,允许外部通过组及名称访问和控制容器中Trigger和JobDetail。 68 | 69 | ![](http://oeckzejn4.bkt.clouddn.com/20180623152976544130422.png) 70 | Scheduler 可以将 Trigger 绑定到某一 JobDetail 中,这样当 Trigger 触发时,对应的 Job 就被执行。可以通过 SchedulerFactory创建一个 Scheduler 实例。Scheduler 拥有一个 SchedulerContext,它类似于 ServletContext,保存着 Scheduler 上下文信息,Job 和 Trigger 都可以访问 SchedulerContext 内的信息。SchedulerContext 内部通过一个 Map,以键值对的方式维护这些上下文数据,SchedulerContext 为保存和获取数据提供了多个 put() 和 getXxx() 的方法。可以通过`Scheduler# getContext()`获取对应的`SchedulerContext`实例; 71 | 72 | #### ThreadPool 73 | Scheduler 使用一个线程池作为任务运行的基础设施,任务通过共享线程池中的线程提高运行效率。 74 | 75 | #### 进行一个定时任务的简单实例 76 | ```java 77 | public class JobTest implements BaseJob { 78 | private static org.slf4j.Logger log = LoggerFactory.getLogger(JobTest.class); 79 | 80 | @Override 81 | public void execute(JobExecutionContext context) throws JobExecutionException { 82 | log.error("JobTest 执行时间: " + new Date()); 83 | } 84 | } 85 | ``` 86 | ```java 87 | @Test 88 | public void quartzTest() throws SchedulerException{ 89 | // 1. 创建 SchedulerFactory 90 | SchedulerFactory factory = new StdSchedulerFactory(); 91 | // 2. 从工厂中获取调度器实例 92 | Scheduler scheduler = factory.getScheduler(); 93 | 94 | // 3. 引进作业程序 95 | JobDetail jobDetail = JobBuilder.newJob(JobTest.class).withDescription("this is a ram job") //job的描述 96 | .withIdentity("jobTest", "jobTestGrip") //job 的name和group 97 | .build(); 98 | 99 | long time= System.currentTimeMillis() + 3*1000L; //3秒后启动任务 100 | Date statTime = new Date(time); 101 | 102 | // 4. 创建Trigger 103 | //使用SimpleScheduleBuilder或者CronScheduleBuilder 104 | Trigger trigger = TriggerBuilder.newTrigger() 105 | .withDescription("this is a cronTrigger") 106 | .withIdentity("jobTrigger", "jobTriggerGroup") 107 | //.withSchedule(SimpleScheduleBuilder.simpleSchedule()) 108 | .startAt(statTime) //默认当前时间启动 109 | .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次 110 | .build(); 111 | 112 | // 5. 注册任务和定时器 113 | scheduler.scheduleJob(jobDetail, trigger); 114 | 115 | // 6. 启动 调度器 116 | scheduler.start(); 117 | _log.info("启动时间 : " + new Date()); 118 | } 119 | ``` 120 | 121 | 122 | ## 三、Quartz 设计分析 123 | ### quartz.properties文件 124 | Quartz 有一个叫做`quartz.properties`的配置文件,它允许你修改框架运行时环境。缺省是使用 `Quartz.jar` 里面的`quartz.properties` 文件。你应该创建一个 `quartz.properties` 文件的副本并且把它放入你工程的 classes 目录中以便类装载器找到它。 125 | ```xml 126 | // 调度标识名 集群中每一个实例都必须使用相同的名称 (区分特定的调度器实例) 127 | org.quartz.scheduler.instanceName:DefaultQuartzScheduler 128 | // ID设置为自动获取 每一个必须不同 (所有调度器实例中是唯一的) 129 | org.quartz.scheduler.instanceId :AUTO 130 | // 数据保存方式为持久化 131 | org.quartz.jobStore.class :org.quartz.impl.jdbcjobstore.JobStoreTX 132 | // 表的前缀 133 | org.quartz.jobStore.tablePrefix : QRTZ_ 134 | // 设置为TRUE不会出现序列化非字符串类到 BLOB 时产生的类版本问题 135 | // org.quartz.jobStore.useProperties : true 136 | // 加入集群 true 为集群 false不是集群 137 | org.quartz.jobStore.isClustered : false 138 | // 调度实例失效的检查时间间隔 139 | org.quartz.jobStore.clusterCheckinInterval:20000 140 | // 容许的最大作业延长时间 141 | org.quartz.jobStore.misfireThreshold :60000 142 | // ThreadPool 实现的类名 143 | org.quartz.threadPool.class:org.quartz.simpl.SimpleThreadPool 144 | // 线程数量 145 | org.quartz.threadPool.threadCount : 10 146 | // 线程优先级 147 | // threadPriority 属性的最大值是常量 java.lang.Thread.MAX_PRIORITY,等于10。最小值为常量 java.lang.Thread.MIN_PRIORITY,为1 148 | org.quartz.threadPool.threadPriority : 5 149 | // 自创建父线程 150 | //org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true 151 | // 数据库别名 152 | org.quartz.jobStore.dataSource : qzDS 153 | // 设置数据源 154 | org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver 155 | org.quartz.dataSource.qzDS.URL:jdbc:mysql://localhost:3306/quartz 156 | org.quartz.dataSource.qzDS.user:root 157 | org.quartz.dataSource.qzDS.password:123456 158 | org.quartz.dataSource.qzDS.maxConnection:10 159 | ``` 160 | 161 | ### Quartz 调度器 162 | Quartz框架的核心是调度器。调度器负责管理Quartz应用运行时环境。启动时,框架初始化一套`worker`线程,这套线程被调度器用来执行预定的作业。这就是 Quartz 怎样能并发运行多个作业的原理。Quartz 依赖一套松耦合的线程池管理部件来管理线程环境。 163 | 164 | ### 两种作业存储方式 165 | #### 1. RAMJobStore 166 | - 通常的内存来持久化调度程序信息。这种作业存储类型最容易配置、构造和运行。 167 | - 因为这种方式的调度程序信息是被分配到 JVM 内存中,所以,当应用程序停止运行时,所有调度信息将被丢失。如果你需要在重新启动之间持久化调度信息,则将需要第二种类型的作业存储。 168 | #### 2. JDBC作业存储 169 | - 需要JDBC驱动程序和后台数据库来持久化调度程序信息(支持集群) 170 | ##### 表关系和解释 171 | ![表关系](http://oeckzejn4.bkt.clouddn.com/20180624152983097394657.png) 172 | ```table 173 | 表名称 | 说明 174 | qrtz_blob_triggers | Trigger作为Blob类型存储(用于Quartz用户用JDBC创建他们自己定制的Trigger类型,JobStore 并不知道如何存储实例的时候) 175 | qrtz_calendars | 以Blob类型存储Quartz的Calendar日历信息, quartz可配置一个日历来指定一个时间范围 176 | qrtz_cron_triggers | 存储Cron Trigger,包括Cron表达式和时区信息。 177 | qrtz_fired_triggers | 存储与已触发的Trigger相关的状态信息,以及相联Job的执行信息 178 | qrtz_job_details | 存储每一个已配置的Job的详细信息 179 | qrtz_locks | 存储程序的非观锁的信息(假如使用了悲观锁) 180 | qrtz_paused_trigger_graps | 存储已暂停的Trigger组的信息 181 | qrtz_scheduler_state | 存储少量的有关 Scheduler的状态信息,和别的 Scheduler 实例(假如是用于一个集群中) 182 | qrtz_simple_triggers | 存储简单的 Trigger,包括重复次数,间隔,以及已触的次数 183 | qrtz_triggers | 存储已配置的 Trigger的信息 184 | qrzt_simprop_triggers 185 | ``` 186 | 187 | ## 利用 SpringBoot + Quartz 搭建的界面化的 Demo 188 | 在网上找到一个搭好的 Demo,感谢大神!原文: [Spring Boot集成持久化Quartz定时任务管理和界面展示](https://blog.csdn.net/u012907049/article/details/73801122/) 189 | #### 本工程所用到的技术或工具 190 | > Spring Boot 191 | > Mybatis 192 | > Quartz 193 | > PageHelper 194 | > VueJS 195 | > ElementUI 196 | > MySql数据库 197 | 198 | #### 先看图: 199 | ![效果图.png](http://oeckzejn4.bkt.clouddn.com/20180624152983342415181.png) 200 | ![新建任务.png](http://oeckzejn4.bkt.clouddn.com/20180624152983345244946.png) 201 | 202 | #### 源码地址 203 | - [我的github](https://github.com/chuanqiang/QuartzDemo) 204 | - [我的码云](https://gitee.com/zhang_cq/QuartzDemo) 205 | - [原项目github](https://github.com/tjfy1992/SpringBootQuartz) 206 | 207 | ## 参考资料 208 | - [quartz原理揭秘和源码解读](https://www.jianshu.com/p/bab8e4e32952#fn3) 209 | - [quartz由浅入深](https://blog.csdn.net/guolong1983811/article/details/51501346) 210 | - [Quartz官方文档](https://www.w3cschool.cn/quartz_doc/) 211 | - [Spring Boot集成持久化Quartz定时任务管理和界面展示](https://blog.csdn.net/u012907049/article/details/73801122/) -------------------------------------------------------------------------------- /demo/.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /demo/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /demo/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chuanqiang/QuartzDemo/842eec7c74c6e6bd9baf1dcfc321a67e72ec67ed/demo/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /demo/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip 2 | -------------------------------------------------------------------------------- /demo/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /demo/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /demo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | demo 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | demo 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.0.M2 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.mybatis.spring.boot 30 | mybatis-spring-boot-starter 31 | 1.3.0 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-quartz 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-web 40 | 41 | 42 | 43 | mysql 44 | mysql-connector-java 45 | runtime 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-test 50 | test 51 | 52 | 53 | 54 | com.github.pagehelper 55 | pagehelper 56 | 5.0.0 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | org.springframework.boot 65 | spring-boot-maven-plugin 66 | 67 | 68 | 69 | 70 | src/main/java 71 | 72 | **/*.xml 73 | 74 | true 75 | 76 | 77 | 78 | src/main/resources 79 | true 80 | 81 | 82 | 83 | 84 | 85 | 86 | spring-snapshots 87 | Spring Snapshots 88 | https://repo.spring.io/snapshot 89 | 90 | true 91 | 92 | 93 | 94 | spring-milestones 95 | Spring Milestones 96 | https://repo.spring.io/milestone 97 | 98 | false 99 | 100 | 101 | 102 | 103 | 104 | 105 | spring-snapshots 106 | Spring Snapshots 107 | https://repo.spring.io/snapshot 108 | 109 | true 110 | 111 | 112 | 113 | spring-milestones 114 | Spring Milestones 115 | https://repo.spring.io/milestone 116 | 117 | false 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.context.annotation.ComponentScan; 7 | 8 | @ComponentScan("com.example.demo") 9 | @MapperScan("com.example.demo.dao") 10 | @SpringBootApplication 11 | 12 | /** 13 | * @Description: springboot 启动类 14 | * @Author: zhang_cq 15 | * @Date: 2018/6/22 下午4:12 16 | */ 17 | public class DemoApplication { 18 | 19 | public static void main(String[] args) { 20 | SpringApplication.run(DemoApplication.class, args); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/SchedulerConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import java.io.IOException; 4 | import java.util.Properties; 5 | 6 | import org.quartz.Scheduler; 7 | import org.quartz.ee.servlet.QuartzInitializerListener; 8 | import org.springframework.beans.factory.config.PropertiesFactoryBean; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.core.io.ClassPathResource; 12 | import org.springframework.scheduling.quartz.SchedulerFactoryBean; 13 | 14 | /** 15 | * @Author: zhang_cq 16 | */ 17 | @Configuration 18 | public class SchedulerConfig { 19 | 20 | @Bean(name = "SchedulerFactory") 21 | public SchedulerFactoryBean schedulerFactoryBean() throws IOException { 22 | SchedulerFactoryBean factory = new SchedulerFactoryBean(); 23 | factory.setQuartzProperties(quartzProperties()); 24 | return factory; 25 | } 26 | 27 | @Bean 28 | public Properties quartzProperties() throws IOException { 29 | PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); 30 | propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); 31 | //在quartz.properties中的属性被读取并注入后再初始化对象 32 | propertiesFactoryBean.afterPropertiesSet(); 33 | return propertiesFactoryBean.getObject(); 34 | } 35 | 36 | /** 37 | * @Description: quartz初始化监听器 38 | */ 39 | @Bean 40 | public QuartzInitializerListener executorListener() { 41 | return new QuartzInitializerListener(); 42 | } 43 | 44 | 45 | /** 46 | * @Description: 通过SchedulerFactoryBean获取Scheduler的实例 47 | */ 48 | @Bean(name = "Scheduler") 49 | public Scheduler scheduler() throws IOException { 50 | return schedulerFactoryBean().getScheduler(); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/controller/JobController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.quartz.CronScheduleBuilder; 7 | import org.quartz.CronTrigger; 8 | import org.quartz.JobBuilder; 9 | import org.quartz.JobDetail; 10 | import org.quartz.JobKey; 11 | import org.quartz.Scheduler; 12 | import org.quartz.SchedulerException; 13 | import org.quartz.TriggerBuilder; 14 | import org.quartz.TriggerKey; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.beans.factory.annotation.Qualifier; 19 | import org.springframework.web.bind.annotation.GetMapping; 20 | import org.springframework.web.bind.annotation.PostMapping; 21 | import org.springframework.web.bind.annotation.RequestMapping; 22 | import org.springframework.web.bind.annotation.RequestParam; 23 | import org.springframework.web.bind.annotation.RestController; 24 | 25 | import com.example.demo.entity.JobAndTrigger; 26 | import com.example.demo.job.BaseJob; 27 | import com.example.demo.service.IJobAndTriggerService; 28 | import com.github.pagehelper.PageInfo; 29 | 30 | 31 | @RestController 32 | @RequestMapping(value = "/job") 33 | 34 | /** 35 | * @Description: 定时任务管理 controller 36 | * @Author: zhang_cq 37 | * @Date: 2018/6/22 下午4:16 38 | */ 39 | public class JobController { 40 | @Autowired 41 | private IJobAndTriggerService iJobAndTriggerService; 42 | 43 | /** 44 | * 加入Qulifier注解,通过名称注入bean 45 | */ 46 | @Autowired 47 | @Qualifier("Scheduler") 48 | private Scheduler scheduler; 49 | 50 | private static Logger log = LoggerFactory.getLogger(JobController.class); 51 | 52 | /** 53 | * @Description: add a job 54 | */ 55 | @PostMapping(value = "/addjob") 56 | public void addjob( 57 | @RequestParam(value = "jobClassName") String jobClassName, 58 | @RequestParam(value = "jobGroupName") String jobGroupName, 59 | @RequestParam(value = "cronExpression") String cronExpression) 60 | throws Exception { 61 | addJob(jobClassName, jobGroupName, cronExpression); 62 | } 63 | 64 | /** 65 | * @Description: add a job 66 | * @param jobClassName 任务名称 67 | * @param jobGroupName 分组名称 68 | * @param cronExpression cron表达式 69 | */ 70 | public void addJob(String jobClassName, String jobGroupName, String cronExpression) throws Exception { 71 | 72 | // 启动调度器 73 | scheduler.start(); 74 | 75 | //构建job信息 76 | JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobClassName, jobGroupName).build(); 77 | 78 | //表达式调度构建器(即任务执行的时间) 79 | CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression); 80 | 81 | //按新的cronExpression表达式构建一个新的trigger 82 | CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName, jobGroupName).withSchedule(scheduleBuilder).build(); 83 | 84 | try { 85 | scheduler.scheduleJob(jobDetail, trigger); 86 | } catch (SchedulerException e) { 87 | log.info("创建定时任务失败" + e); 88 | throw new Exception("创建定时任务失败"); 89 | } 90 | } 91 | 92 | /** 93 | * @Description: 暂定任务 94 | */ 95 | @PostMapping(value = "/pausejob") 96 | public void pausejob(@RequestParam(value = "jobClassName") String jobClassName, @RequestParam(value = "jobGroupName") String jobGroupName) throws Exception { 97 | jobPause(jobClassName, jobGroupName); 98 | } 99 | 100 | public void jobPause(String jobClassName, String jobGroupName) throws Exception { 101 | scheduler.pauseJob(JobKey.jobKey(jobClassName, jobGroupName)); 102 | } 103 | 104 | /** 105 | * @Description: 恢复任务 106 | */ 107 | @PostMapping(value = "/resumejob") 108 | public void resumejob(@RequestParam(value = "jobClassName") String jobClassName, @RequestParam(value = "jobGroupName") String jobGroupName) throws Exception { 109 | jobresume(jobClassName, jobGroupName); 110 | } 111 | 112 | public void jobresume(String jobClassName, String jobGroupName) throws Exception { 113 | scheduler.resumeJob(JobKey.jobKey(jobClassName, jobGroupName)); 114 | } 115 | 116 | /** 117 | * @Description: 更新任务 118 | */ 119 | @PostMapping(value = "/reschedulejob") 120 | public void rescheduleJob(@RequestParam(value = "jobClassName") String jobClassName, 121 | @RequestParam(value = "jobGroupName") String jobGroupName, 122 | @RequestParam(value = "cronExpression") String cronExpression) throws Exception { 123 | jobreschedule(jobClassName, jobGroupName, cronExpression); 124 | } 125 | 126 | public void jobreschedule(String jobClassName, String jobGroupName, String cronExpression) throws Exception { 127 | try { 128 | TriggerKey triggerKey = TriggerKey.triggerKey(jobClassName, jobGroupName); 129 | // 表达式调度构建器 130 | CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression); 131 | 132 | CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); 133 | 134 | // 按新的cronExpression表达式重新构建trigger 135 | trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); 136 | 137 | // 按新的trigger重新设置job执行 138 | scheduler.rescheduleJob(triggerKey, trigger); 139 | } catch (SchedulerException e) { 140 | log.info("更新定时任务失败" + e); 141 | throw new Exception("更新定时任务失败"); 142 | } 143 | } 144 | 145 | /** 146 | * @Description: 删除任务 147 | */ 148 | @PostMapping(value = "/deletejob") 149 | public void deletejob(@RequestParam(value = "jobClassName") String jobClassName, @RequestParam(value = "jobGroupName") String jobGroupName) throws Exception { 150 | jobdelete(jobClassName, jobGroupName); 151 | } 152 | 153 | public void jobdelete(String jobClassName, String jobGroupName) throws Exception { 154 | scheduler.pauseTrigger(TriggerKey.triggerKey(jobClassName, jobGroupName)); 155 | scheduler.unscheduleJob(TriggerKey.triggerKey(jobClassName, jobGroupName)); 156 | scheduler.deleteJob(JobKey.jobKey(jobClassName, jobGroupName)); 157 | } 158 | 159 | /** 160 | * @Description: 查找任务 161 | */ 162 | @GetMapping(value = "/queryjob") 163 | public Map queryjob(@RequestParam(value = "pageNum") Integer pageNum, @RequestParam(value = "pageSize") Integer pageSize) { 164 | PageInfo jobAndTrigger = iJobAndTriggerService.getJobAndTriggerDetails(pageNum, pageSize); 165 | Map map = new HashMap(); 166 | map.put("JobAndTrigger", jobAndTrigger); 167 | map.put("number", jobAndTrigger.getTotal()); 168 | return map; 169 | } 170 | 171 | /** 172 | * @Description: 通过反射机制实例化 Job 173 | */ 174 | public static BaseJob getClass(String classname) throws Exception { 175 | Class class1 = Class.forName(classname); 176 | return (BaseJob) class1.newInstance(); 177 | } 178 | 179 | 180 | } 181 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/dao/JobAndTriggerMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.dao; 2 | 3 | import java.util.List; 4 | 5 | import com.example.demo.entity.JobAndTrigger; 6 | 7 | public interface JobAndTriggerMapper { 8 | List getJobAndTriggerDetails(); 9 | } 10 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/entity/JobAndTrigger.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.entity; 2 | 3 | import java.math.BigInteger; 4 | 5 | public class JobAndTrigger { 6 | private String JOB_NAME; 7 | private String JOB_GROUP; 8 | private String JOB_CLASS_NAME; 9 | private String TRIGGER_NAME; 10 | private String TRIGGER_GROUP; 11 | private BigInteger REPEAT_INTERVAL; 12 | private BigInteger TIMES_TRIGGERED; 13 | private String CRON_EXPRESSION; 14 | private String TIME_ZONE_ID; 15 | 16 | public String getJOB_NAME() { 17 | return JOB_NAME; 18 | } 19 | public void setJOB_NAME(String jOB_NAME) { 20 | JOB_NAME = jOB_NAME; 21 | } 22 | public String getJOB_GROUP() { 23 | return JOB_GROUP; 24 | } 25 | public void setJOB_GROUP(String jOB_GROUP) { 26 | JOB_GROUP = jOB_GROUP; 27 | } 28 | public String getJOB_CLASS_NAME() { 29 | return JOB_CLASS_NAME; 30 | } 31 | public void setJOB_CLASS_NAME(String jOB_CLASS_NAME) { 32 | JOB_CLASS_NAME = jOB_CLASS_NAME; 33 | } 34 | public String getTRIGGER_NAME() { 35 | return TRIGGER_NAME; 36 | } 37 | public void setTRIGGER_NAME(String tRIGGER_NAME) { 38 | TRIGGER_NAME = tRIGGER_NAME; 39 | } 40 | public String getTRIGGER_GROUP() { 41 | return TRIGGER_GROUP; 42 | } 43 | public void setTRIGGER_GROUP(String tRIGGER_GROUP) { 44 | TRIGGER_GROUP = tRIGGER_GROUP; 45 | } 46 | public BigInteger getREPEAT_INTERVAL() { 47 | return REPEAT_INTERVAL; 48 | } 49 | public void setREPEAT_INTERVAL(BigInteger rEPEAT_INTERVAL) { 50 | REPEAT_INTERVAL = rEPEAT_INTERVAL; 51 | } 52 | public BigInteger getTIMES_TRIGGERED() { 53 | return TIMES_TRIGGERED; 54 | } 55 | public void setTIMES_TRIGGERED(BigInteger tIMES_TRIGGERED) { 56 | TIMES_TRIGGERED = tIMES_TRIGGERED; 57 | } 58 | public String getCRON_EXPRESSION() { 59 | return CRON_EXPRESSION; 60 | } 61 | public void setCRON_EXPRESSION(String cRON_EXPRESSION) { 62 | CRON_EXPRESSION = cRON_EXPRESSION; 63 | } 64 | public String getTIME_ZONE_ID() { 65 | return TIME_ZONE_ID; 66 | } 67 | public void setTIME_ZONE_ID(String tIME_ZONE_ID) { 68 | TIME_ZONE_ID = tIME_ZONE_ID; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/job/BaseJob.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.job; 2 | 3 | import org.quartz.Job; 4 | import org.quartz.JobExecutionContext; 5 | import org.quartz.JobExecutionException; 6 | 7 | public interface BaseJob extends Job{ 8 | void execute(JobExecutionContext context) throws JobExecutionException; 9 | } 10 | 11 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/job/HelloJob.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.job; 2 | 3 | import java.util.Date; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.quartz.JobExecutionContext; 7 | import org.quartz.JobExecutionException; 8 | 9 | public class HelloJob implements BaseJob { 10 | 11 | private static Logger _log = LoggerFactory.getLogger(HelloJob.class); 12 | 13 | public HelloJob() { 14 | 15 | } 16 | 17 | public void execute(JobExecutionContext context) throws JobExecutionException { 18 | _log.error("Hello Job执行时间: " + new Date()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/job/JobTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.job; 2 | 3 | import org.quartz.JobExecutionContext; 4 | import org.quartz.JobExecutionException; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.util.Date; 8 | 9 | public class JobTest implements BaseJob { 10 | private static org.slf4j.Logger log = LoggerFactory.getLogger(JobTest.class); 11 | 12 | @Override 13 | public void execute(JobExecutionContext context) throws JobExecutionException { 14 | log.error("JobTest 执行时间: " + new Date()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/job/MyJobOne.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.job; 2 | 3 | import org.quartz.JobExecutionContext; 4 | import org.quartz.JobExecutionException; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.util.Date; 8 | 9 | public class MyJobOne implements BaseJob { 10 | private static org.slf4j.Logger log = LoggerFactory.getLogger(MyJobOne.class); 11 | 12 | @Override 13 | public void execute(JobExecutionContext context) throws JobExecutionException { 14 | log.error("MyJobOne 执行时间: " + new Date()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/job/NewJob.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.job; 2 | 3 | import java.util.Date; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.quartz.JobExecutionContext; 7 | import org.quartz.JobExecutionException; 8 | 9 | public class NewJob implements BaseJob { 10 | 11 | private static Logger _log = LoggerFactory.getLogger(NewJob.class); 12 | 13 | public NewJob() { 14 | 15 | } 16 | 17 | public void execute(JobExecutionContext context) 18 | throws JobExecutionException { 19 | _log.error("New Job执行时间: " + new Date()); 20 | } 21 | } -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/mapper/JobMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 21 | 22 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/service/IJobAndTriggerService.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service; 2 | 3 | 4 | import com.example.demo.entity.JobAndTrigger; 5 | import com.github.pagehelper.PageInfo; 6 | 7 | public interface IJobAndTriggerService { 8 | /** 9 | * @Description: 获取调度任务信息 10 | * @Author: zhang_cq 11 | * @Date: 2018/6/22 下午4:13 12 | */ 13 | PageInfo getJobAndTriggerDetails(int pageNum, int pageSize); 14 | } 15 | -------------------------------------------------------------------------------- /demo/src/main/java/com/example/demo/service/impl/JobAndTriggerImpl.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.service.impl; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import com.example.demo.dao.JobAndTriggerMapper; 9 | import com.example.demo.entity.JobAndTrigger; 10 | import com.example.demo.service.IJobAndTriggerService; 11 | import com.github.pagehelper.PageHelper; 12 | import com.github.pagehelper.PageInfo; 13 | 14 | 15 | @Service 16 | public class JobAndTriggerImpl implements IJobAndTriggerService { 17 | 18 | @Autowired 19 | private JobAndTriggerMapper jobAndTriggerMapper; 20 | 21 | public PageInfo getJobAndTriggerDetails(int pageNum, int pageSize) { 22 | PageHelper.startPage(pageNum, pageSize); 23 | List list = jobAndTriggerMapper.getJobAndTriggerDetails(); 24 | PageInfo page = new PageInfo(list); 25 | return page; 26 | } 27 | } -------------------------------------------------------------------------------- /demo/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:mysql://127.0.0.1:3306/quartz?characterEncoding=utf8 4 | username: root 5 | password: 111111 6 | driver-class-name: com.mysql.jdbc.Driver 7 | 8 | mybatis: 9 | mapper-locations: 10 | - classpath:com/example/demo/mapper/*.xml 11 | type-aliases-package: com.example.demo.entity 12 | 13 | server: 14 | port: 8010 15 | 16 | logging.level.com.example.demo.mapper: debug 17 | -------------------------------------------------------------------------------- /demo/src/main/resources/log4j.yml: -------------------------------------------------------------------------------- 1 | Loggers: 2 | Root: 3 | level: debug -------------------------------------------------------------------------------- /demo/src/main/resources/quartz.properties: -------------------------------------------------------------------------------- 1 | # 固定前缀org.quartz 2 | # 主要分为scheduler、threadPool、jobStore、plugin等部分 3 | # 4 | # 5 | org.quartz.scheduler.instanceName = DefaultQuartzScheduler 6 | org.quartz.scheduler.rmi.export = false 7 | org.quartz.scheduler.rmi.proxy = false 8 | org.quartz.scheduler.wrapJobExecutionInUserTransaction = false 9 | 10 | # 实例化ThreadPool时,使用的线程类为SimpleThreadPool 11 | org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool 12 | 13 | # threadCount和threadPriority将以setter的形式注入ThreadPool实例 14 | # 并发个数 15 | org.quartz.threadPool.threadCount = 5 16 | # 优先级 17 | org.quartz.threadPool.threadPriority = 5 18 | org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true 19 | 20 | org.quartz.jobStore.misfireThreshold = 5000 21 | 22 | # 默认存储在内存中 23 | #org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore 24 | 25 | #持久化 26 | org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX 27 | 28 | org.quartz.jobStore.tablePrefix = QRTZ_ 29 | 30 | org.quartz.jobStore.dataSource = qzDS 31 | 32 | org.quartz.dataSource.qzDS.driver = com.mysql.jdbc.Driver 33 | 34 | org.quartz.dataSource.qzDS.URL = jdbc:mysql://127.0.0.1:3306/quartz?useUnicode=true&characterEncoding=UTF-8 35 | 36 | org.quartz.dataSource.qzDS.user = root 37 | 38 | org.quartz.dataSource.qzDS.password = 111111 39 | 40 | org.quartz.dataSource.qzDS.maxConnections = 10 -------------------------------------------------------------------------------- /demo/src/main/resources/static/JobManager.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | QuartzDemo 6 | 7 | 8 | 9 | 10 | 11 | 18 | 19 | 20 | 21 |
22 | 23 |
24 | 查询 25 | 添加 26 | 27 |
28 | 29 |
30 | 31 |
32 | 33 | 39 | 44 | 45 | 46 | 50 | 51 | 52 | 56 | 57 | 58 | 62 | 63 | 64 | 68 | 69 | 70 | 74 | 75 | 76 | 80 | 81 | 82 | 83 | 104 | 105 | 106 | 107 |
108 | 116 | 117 |
118 |
119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 148 | 149 | 150 |
151 | 152 |
153 |

© Quartz 任务管理

154 |
155 | 156 | 303 | 304 | 305 | 306 | -------------------------------------------------------------------------------- /demo/src/test/java/com/example/demo/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import com.example.demo.job.JobTest; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.quartz.*; 7 | import org.quartz.impl.StdSchedulerFactory; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import java.util.Date; 14 | 15 | @RunWith(SpringRunner.class) 16 | @SpringBootTest 17 | public class DemoApplicationTests { 18 | private static Logger _log = LoggerFactory.getLogger(DemoApplicationTests.class); 19 | @Test 20 | public void contextLoads() { 21 | } 22 | 23 | @Test 24 | public void quartzTest() throws SchedulerException{ 25 | // 1. 创建 SchedulerFactory 26 | SchedulerFactory factory = new StdSchedulerFactory(); 27 | // 2. 从工厂中获取调度器实例 28 | Scheduler scheduler = factory.getScheduler(); 29 | 30 | // 3. 引进作业程序 31 | JobDetail jobDetail = JobBuilder.newJob(JobTest.class).withDescription("this is a ram job") //job的描述 32 | .withIdentity("jobTest", "jobTestGrip") //job 的name和group 33 | .build(); 34 | 35 | long time= System.currentTimeMillis() + 3*1000L; //3秒后启动任务 36 | Date statTime = new Date(time); 37 | 38 | // 4. 创建Trigger 39 | //使用SimpleScheduleBuilder或者CronScheduleBuilder 40 | Trigger trigger = TriggerBuilder.newTrigger() 41 | .withDescription("this is a cronTrigger") 42 | .withIdentity("jobTrigger", "jobTriggerGroup") 43 | //.withSchedule(SimpleScheduleBuilder.simpleSchedule()) 44 | .startAt(statTime) //默认当前时间启动 45 | .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次 46 | .build(); 47 | 48 | // 5. 注册任务和定时器 49 | scheduler.scheduleJob(jobDetail, trigger); 50 | 51 | // 6. 启动 调度器 52 | scheduler.start(); 53 | _log.info("启动时间 : " + new Date()); 54 | } 55 | } 56 | --------------------------------------------------------------------------------