【Quartz学习总结】——入门程序

2024-08-26 15:48

本文主要是介绍【Quartz学习总结】——入门程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

   

   Quartz是什么

    Quartz是OpenSystemphony开源组织在Job scheduling领域哟一个开源项目,他可以域J2EE与J2SE应用程序相结合也可以单独使用。Quartz可以用来创建简单活为运行十个、百个,甚至好几万个Jobs这样复杂的日程序表。Jobs可以做成标准的Java组件或EJBs.

    Quartz是一个任务日程管理系统,一个预先确定(被纳入日程)的时间到达时,负责执行(或通知)其他软件组件的系统。

    Quartz是一个小java库发布文件(.jar文件),这个库文件包含了所有uartz核心功能。这些功能注解接口(API)是Scheduler接口。他提供了简单的操作,例如:将任务纳入日程或者从日程中取消,开始、停止、暂停日程进度。

   核心接口

    Scheduler——核心调度器

    Job——任务

    JobDetai——任务描述

    Trigger——触发器

   执行过程

   

    Trigger

    SimpleTrigger   简单触发

    SimpleTrigger用来触发只需执行一次或者在给定时间触发并且重复N次且每次执行延迟一定时间的任务。
如果你想让触发器在2014年1月11日,上午11:23:54秒执行,然后每个隔10秒钟重复执行一次,并且这样重复5次。那么SimpleTrigger 就可以满足你的要求。

    CronTrigger    表达式触发

    如果你需要像日历那样按日程来触发任务,而不是像SimpleTrigger 那样每隔特定的间隔时间触发,CronTriggers通常比SimpleTrigger更有用。
使用CronTrigger,你可以指定诸如“每个周五中午”,或者“每个工作日的9:30”或者“从每个周一、周三、周五的上午9:00到上午10:00之间每隔五分钟”这样日程安排来触发。甚至,象SimpleTrigger一样,CronTrigger也有一个startTime以指定日程从什么时候开始,也有一个(可选的)endTime以指定何时日程不再继续。

   关于时间表达式的编写:在下一篇博客中进行详细的介绍。

   可以这样说:凡是SimpleTrigger能完成的任务,CronTrigger表达式都可以完成

  官方Demo演示

   添加依赖:

        <dependency><groupId>org.quartz-scheduler</groupId><artifactId>quartz</artifactId><version>2.2.1</version></dependency>

   Job类代码:

    

/* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * *   http://www.apache.org/licenses/LICENSE-2.0 *   * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License.* */package cn.itcast.quartz.example;import java.util.Date;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;/*** <p>* This is just a simple job that says "Hello" to the world.* </p>* * @author Bill Kratzer*/
public class HelloJob implements Job {private static Logger _log = LoggerFactory.getLogger(HelloJob.class);/*** <p>* Empty constructor for job initilization* </p>* <p>* Quartz requires a public empty constructor so that the* scheduler can instantiate the class whenever it needs.* </p>*/public HelloJob() {}/*** <p>* Called by the <code>{@link org.quartz.Scheduler}</code> when a* <code>{@link org.quartz.Trigger}</code> fires that is associated with* the <code>Job</code>.* </p>* * @throws JobExecutionException*             if there is an exception while executing the job.*/public void execute(JobExecutionContext context)throws JobExecutionException {// Say Hello to the World and display the date/time_log.info("Hello World! - " + new Date());}}

  表达式触发器代码:

   

/* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * *   http://www.apache.org/licenses/LICENSE-2.0 *   * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License.* */package cn.itcast.quartz.example;import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.DateBuilder.evenMinuteDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.Date;/*** This Example will demonstrate how to start and shutdown the Quartz scheduler and how to schedule* a job to run in Quartz.* * @author Bill Kratzer*/
public class SimpleCronExample {public void run() throws Exception {Logger log = LoggerFactory.getLogger(SimpleCronExample.class);log.info("------- Initializing ----------------------");// 定义调度器SchedulerFactory sf = new StdSchedulerFactory();Scheduler sched = sf.getScheduler();log.info("------- Initialization Complete -----------");// 获取当前时间的下一分钟Date runTime = evenMinuteDate(new Date());log.info("------- Scheduling Job  -------------------");// 定义jobJobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build();// 定义触发器,每2秒执行一次Trigger trigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0 0/1 * * * ?")).build();// 将job注册到调度器sched.scheduleJob(job, trigger);log.info(job.getKey() + " will run at: " + runTime);// 启动调度器sched.start();log.info("------- Started Scheduler -----------------");// 等待1分钟log.info("------- Waiting 60 seconds... -------------");try {Thread.sleep(60L * 1000L);} catch (Exception e) {//}// 关闭调度器log.info("------- Shutting Down ---------------------");sched.shutdown(true);log.info("------- Shutdown Complete -----------------");}public static void main(String[] args) throws Exception {SimpleCronExample example = new SimpleCronExample();example.run();}}

   简单才触发器代码:

   

/* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * *   http://www.apache.org/licenses/LICENSE-2.0 *   * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License.* */package cn.itcast.quartz.example;import static org.quartz.DateBuilder.evenMinuteDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.Date;/*** This Example will demonstrate how to start and shutdown the Quartz scheduler and how to schedule* a job to run in Quartz.* * @author Bill Kratzer*/
public class SimpleExample {public void run() throws Exception {Logger log = LoggerFactory.getLogger(SimpleExample.class);log.info("------- Initializing ----------------------");// 定义调度器SchedulerFactory sf = new StdSchedulerFactory();Scheduler sched = sf.getScheduler();log.info("------- Initialization Complete -----------");// 获取当前时间的下一分钟Date runTime = evenMinuteDate(new Date());log.info("------- Scheduling Job  -------------------");// 定义job// 在quartz中,有组的概念,组+job名称 唯一的JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build();// 定义触发器,在下一分钟启动Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build();// 将job注册到调度器sched.scheduleJob(job, trigger);log.info(job.getKey() + " will run at: " + runTime);// 启动调度器sched.start();log.info("------- Started Scheduler -----------------");// 等待65秒log.info("------- Waiting 65 seconds... -------------");try {// wait 65 seconds to show jobThread.sleep(65L * 1000L);// executing...} catch (Exception e) {//}// 关闭调度器log.info("------- Shutting Down ---------------------");sched.shutdown(true);log.info("------- Shutdown Complete -----------------");}public static void main(String[] args) throws Exception {SimpleExample example = new SimpleExample();example.run();}}

   在下一篇博客中详细介绍,表达式触发器中表达式的编写。

这篇关于【Quartz学习总结】——入门程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1108994

相关文章

Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式

《Java通过驱动包(jar包)连接MySQL数据库的步骤总结及验证方式》本文详细介绍如何使用Java通过JDBC连接MySQL数据库,包括下载驱动、配置Eclipse环境、检测数据库连接等关键步骤,... 目录一、下载驱动包二、放jar包三、检测数据库连接JavaJava 如何使用 JDBC 连接 mys

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

JavaSE正则表达式用法总结大全

《JavaSE正则表达式用法总结大全》正则表达式就是由一些特定的字符组成,代表的是一个规则,:本文主要介绍JavaSE正则表达式用法的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录常用的正则表达式匹配符正则表China编程达式常用的类Pattern类Matcher类PatternSynta

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(

Redis 配置文件使用建议redis.conf 从入门到实战

《Redis配置文件使用建议redis.conf从入门到实战》Redis配置方式包括配置文件、命令行参数、运行时CONFIG命令,支持动态修改参数及持久化,常用项涉及端口、绑定、内存策略等,版本8... 目录一、Redis.conf 是什么?二、命令行方式传参(适用于测试)三、运行时动态修改配置(不重启服务

MySQL DQL从入门到精通

《MySQLDQL从入门到精通》通过DQL,我们可以从数据库中检索出所需的数据,进行各种复杂的数据分析和处理,本文将深入探讨MySQLDQL的各个方面,帮助你全面掌握这一重要技能,感兴趣的朋友跟随小... 目录一、DQL 基础:SELECT 语句入门二、数据过滤:WHERE 子句的使用三、结果排序:ORDE

SQL中JOIN操作的条件使用总结与实践

《SQL中JOIN操作的条件使用总结与实践》在SQL查询中,JOIN操作是多表关联的核心工具,本文将从原理,场景和最佳实践三个方面总结JOIN条件的使用规则,希望可以帮助开发者精准控制查询逻辑... 目录一、ON与WHERE的本质区别二、场景化条件使用规则三、最佳实践建议1.优先使用ON条件2.WHERE用