简介
Quartz是OpenSymphony开源组织的一个开源项目,定时任务框架,纯Java语言实现,最新版本为2.3.0。
设计模式
Quartz中使用的设计模式如下:
1.Builder模式
2.Factory模式
3.组件模式
4.链式模式
体系结构
1.调度器:scheduler
2.任务:JobDetail
3.触发器:Trigger,包括SimpleTrigger和CronTrigger
第一个Quartz程序
实现每隔1秒打印一个Hello Worlder
1.创建Maven项目,添加依赖:
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
2.创建HelloWorldJob类
package quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* created by Java-Road
* created in 2018/5/26
*/
public class HelloWorldJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
String strTime = new SimpleDateFormat("HH-mm-ss").format(new Date());
System.out.println( strTime + ":Hello World!");
}
}
3.创建MyScheduler类
package quartz;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
/**
* created by Java-Road
* created in 2018/5/26
*/
public class MyScheduler {
public static void main(String[] args) throws SchedulerException {
//创建调度器Schedule
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
//创建JobDetail实例,并与HelloWordlJob类绑定
JobDetail jobDetail = JobBuilder.newJob(HelloWorldJob.class).withIdentity("job1", "jobGroup1")
.build();
//创建触发器Trigger实例(立即执行,每隔1S执行一次)
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "triggerGroup1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
.build();
//开始执行
scheduler.scheduleJob(jobDetail, trigger);
scheduler.start();
}
}