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

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

Quartz是什么


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

 

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

 

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


  核心接口


   Scheduler——核心调度器


   Job——任务


   JobDetai——任务描述


   Trigger——触发器


执行过程


20170812213226599.png


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  -------------------");
        // 定义job
        JobDetail 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 job
            Thread.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();
    }
}

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

目录
相关文章
|
uml
IDEA使用插件绘制UML类图+PlantUML语法讲解
IDEA使用插件绘制UML类图+PlantUML语法讲解
1570 0
|
6月前
|
消息中间件 缓存 NoSQL
基于Spring Data Redis与RabbitMQ实现字符串缓存和计数功能(数据同步)
总的来说,借助Spring Data Redis和RabbitMQ,我们可以轻松实现字符串缓存和计数的功能。而关键的部分不过是一些"厨房的套路",一旦你掌握了这些套路,那么你就像厨师一样可以准备出一道道饕餮美食了。通过这种方式促进数据处理效率无疑将大大提高我们的生产力。
228 32
|
2月前
|
数据采集 运维 监控
构建企业级Selenium爬虫:基于隧道代理的IP管理架构
构建企业级Selenium爬虫:基于隧道代理的IP管理架构
|
3月前
|
数据采集 存储 监控
初识LightRAG:轻量级知识图谱框架指南
LightRAG创新融合知识图谱与向量检索,显著提升检索精度和可解释性。该框架轻量高效,支持多模态数据处理,提供简洁API便于快速集成。通过结构化关系补充分散语义,有效解决传统RAG系统的关系缺失与语义模糊问题。
|
6月前
|
人工智能 边缘计算 自然语言处理
CodeBuddy全新升级:体验Craft智能体的对话式编程革命
本文介绍了腾讯云代码助手CodeBuddy及其核心功能Craft智能体,展示了其在软件开发中的创新应用。Craft智能体通过自然语言理解、上下文感知的代码补全和多轮对话式调试等功能,显著提升了开发效率。文章详细解析了Craft的技术架构、实战应用、高级功能探索、最佳实践、性能优化策略以及与其他工具的集成。此外,还探讨了Craft在安全性与合规性、企业级定制、多模态编程支持、团队协作模式、边缘计算场景支持等方面的创新实践。Craft智能体代表了软件开发范式的重要转变,通过将自然语言理解与代码生成能力结合,降低
465 1
|
11月前
|
资源调度 前端开发 JavaScript
Bootstrap日期选择器插件bootstrap-datepicker
Bootstrap日期选择器插件bootstrap-datepicker
1048 12
|
缓存 测试技术 Apache
告别卡顿!Python性能测试实战教程,JMeter&Locust带你秒懂性能优化💡
告别卡顿!Python性能测试实战教程,JMeter&Locust带你秒懂性能优化💡
335 1
如何使用IDEA自动生成类图
本文介绍了如何在IntelliJ IDEA中使用快捷键Ctrl+Alt+U自动生成Java类的类图,并提供了截图方法和相关插件的使用说明。
如何使用IDEA自动生成类图
|
自然语言处理
掩码语言模型(MLM)
掩码语言模型(MLM)
|
XML Java 调度
Android开发音效增强中铃声播放Ringtone及声音池调度SoundPool的讲解及实战(超详细 附源码)
Android开发音效增强中铃声播放Ringtone及声音池调度SoundPool的讲解及实战(超详细 附源码)
687 0