【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();
    }
}

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

目录
相关文章
|
存储 负载均衡 监控
分布式定时任务,你了解多少?基于Quartz实现分布式定时任务解决方案!
定时任务系统在应用平台中的重要性不言而喻,特别是互联网电商、金融等行业更是离不开定时任务。在任务数量不多、执行频率不高时,单台服务器完全能够满足。但是随着业务逐渐增加,定时任务系统必须具备高可用和水平扩展的能力,单台服务器已经不能满足需求。因此需要把定时任务系统部署到集群中,实现分布式定时任务系统集群。
6699 1
分布式定时任务,你了解多少?基于Quartz实现分布式定时任务解决方案!
|
8月前
|
搜索推荐 数据安全/隐私保护 Windows
Windows 11安装全流程 Windows版:PE启动盘制作+Win11安装
本教程详解如何用8GB以上U盘制作PE启动盘,并以此安装Windows 11系统。涵盖U盘格式化(NTFS)、PE工具写入、ISO部署、C盘格式化、系统初始化、解压软件安装及数字激活全流程,操作清晰,适配主流硬件。(239字)
7641 7
|
6月前
|
运维 安全 Linux
Linux还是Windows?看懂这两种云服务器安全性的本质差异
在云服务器选型中,Linux与Windows的安全性差异显著:Linux架构权限更严、默认服务少、攻击面小,且恶意软件生态薄弱;Windows则因兼容性需开放更多端口与服务,RDP爆破、SMB漏洞及勒索病毒风险更高。安全首选Linux,兼容优先选Windows。(239字)
754 0
|
11月前
|
存储 人工智能 资源调度
从 0 到 1:搭建具备“指挥+调度”双重属性的 AI 智能体
本文深度解析2026年企业级AI落地关键——兼具“指挥官”(战略拆解)与“调度官”(动态执行)双重能力的Agentic Workflow系统。涵盖分层架构、意图引擎、动态路由、记忆闭环及实战部署,助你打造真正能干事的数字军团中枢。(239字)
777 5
|
存储 前端开发 Java
|
存储 弹性计算 Cloud Native
云原生成本精细化管理实践:企迈科技的成本中心建设之路
企迈实施成本中心建设的项目核心目标不仅是实现云资源的优化配置,还要为管理层提供清晰、实时的成本数据分析,帮助管理层做出更加精准的决策。通过精细化的云成本管控,逐步实现成本降低、资源合理分配和更加高效的云产品使用。
云原生成本精细化管理实践:企迈科技的成本中心建设之路
|
人工智能 物联网
VideoPainter:开源视频修复神器!双分支架构一键修复,对象身份永久在线
VideoPainter 是由香港中文大学、腾讯ARC Lab等机构联合推出的视频修复和编辑框架,基于双分支架构和预训练扩散模型,支持任意长度视频的修复与编辑,具备背景保留、前景生成、文本指导编辑等功能,为视频处理领域带来新的突破。
1278 12
|
开发者 Python
新手困扰?该如何了解github的热门趋势和star排行?
新手困扰?该如何了解github的热门趋势和star排行?
2916 0
|
存储 前端开发 Java
基于springboot的助农管理系统的设计与实现
基于springboot的助农管理系统的设计与实现
|
安全 JavaScript Java
社区老人健康信息管理系统|基于springboot社区老人健康信息管理系统设计与实现(源码+数据库+文档)
社区老人健康信息管理系统|基于springboot社区老人健康信息管理系统设计与实现(源码+数据库+文档)
712 1