在研究公司项目的时候,发现定时任务的实现是用Spring集成Quartz框架来做的。于是就开始了新一波的学习……
一、基本概念
官方介绍:
Quartz is arichly featured,open source job scheduling library that can be integrated within virtually any Java application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as support for JTA transactions and clustering.
简单来说,Quartz是一个完全由Java编写的开源作业调度框架,为在Java应用程序中进行作业调度提供了简单却强大的机制。你可以执行任何你想要执行的任务,比如每天定时给小姐姐或小哥哥发一封想念的邮件。
二、quartz的下载
(1)下载jar包
http://www.quartz-scheduler.org/downloads/ 官网链接 请叫我贴心的小姐姐(认真脸)
(2)用maven依赖引入
三、简单介绍
quart主要有三个核心模块:Scheduler、Job、Trigger
(1) Job
Job就是你要实现的任务类,需要实现org.quartz.job接口,且只需实现接口定义的execute()方法。
(2) Trigger
Trigger执行任务的触发器,比如上面所说的你想每天准点给小姐姐或者小哥哥发一封邮件,Trigger将根据你设置的时间执行该任务。Trigger主要包含两种SimpleTrigger和CronTrigger两种。
(3) Scheduler
Scheduler为任务的调度器,它会将任务job及触发器Trigger整合起来,负责基于Trigger设定的时间来执行Job。
四、举个栗子
1.maven引入依赖
2.创建任务类
public class SendEmailJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("I want to say ……");
}
}
3.主代码
public class QuartzTest {
public static void main(String args[]) throws Exception {
// 创建任务
JobDetail jobDetail = JobBuilder.newJob(SendEmailJob.class) //要执行的任务
.withIdentity("hello", "hello") //名称与组名组成Scheduler中任务的唯一标识
.build();
//创建Trigger
SimpleTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity("hi", "hi") //名称与组名组成Scheduler中Trigger的唯一标识
.withSchedule(
SimpleScheduleBuilder.simpleSchedule() //创建SimpleTrigger
.withIntervalInSeconds(10) //每隔十秒运行一次
.repeatForever()) //重复
.build();
//创建调度器
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//调度任务
scheduler.scheduleJob(jobDetail,trigger);
// 开启调度器
scheduler.start();
Thread.sleep(60000);
//关闭调度器
scheduler.shutdown();
}
}
4.运行结果
I want to say ……
I want to say ……
I want to say ……
I want to say ……
I want to say ……
I want to say ……
I want to say ……
上面的栗子简单的说明了Quartz的基本使用方式。后续将会继续研究Quartz的使用,以及Spring集成Quartz的方法。