Quartz核心原理之架构及基本元素介绍
1 什么是QuartzQuartz是一个作业调度框架,它可以与J2EE和J2SE应用相结合,也可以单独使用。它能够创建多个甚至数万个jobs这样复杂的程序,jobs可以做成标准的java组件或EJBS。Quartz很容易上手,创建一个任务仅需实现Job接口,该接口只有一个方法void execute(JobExecutionContext context) throws JobExecutionException;在java实现类添加作业逻辑,当配置好Job实现类并设置调度时间表后,Quartz将会监控任务的剩余时间,当调度程序确定需要通知需要执行该任务的时候,Quartz将会调用Job实现类的execute方法执行任务。
2 系统设计
Quartz框架的原理主要是通过将Job注册到调度器,再通过触发器策略执行Job,系统设计如下:
https://p3-sign.toutiaoimg.com/tos-cn-i-6w9my0ksvp/b2a82a75727b41439467b241cb635dde~tplv-obj.image?lk3s=3de049d8&traceid=202312051018296DD69447CC4F3670B697&x-expires=2147483647&x-signature=q6rZeOn8chnH3O5omoE9S6x7tQs%3D
3 核心元素介绍
Quartz框架的核心是调度器scheduler,核心的组件包括Job(任务)、JobDetail(任务描述)、Trigger(触发器)。调度器负责管理Quartz应用运行时环境。调度器不是靠自己做所有的工作,而是依赖框架内一些非常重要的部件。Quartz不仅仅是线程和线程管理。为确保可伸缩性,Quartz采用了基于多线程的架构。启动时,框架初始化一套worker线程,这套线程被调度器用来执行预定的作业。这就是Quartz怎样能并发运行多个作业的原理。Quartz依赖一套松耦合的线程池管理部件来管理线程环境。
3.1 Job
Job是一个接口,只有一个方法void execute(JobExecutionContext context) throws JobExecutionException。作业类需要实现接口中的execute方法,JobExecutionContext提供了调度的上下文信息,每一次执行Job都会重新创建一个Job对象实例。如下:
public interface Job {
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Interface.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/**
* <p>
* Called by the {@link Scheduler} when a {@link Trigger}
* fires that is associated with the Job.
* </p>
*
* <p>
* The implementation may wish to set a
* {@link JobExecutionContext#setResult(Object) result} object on the
* {@link JobExecutionContext} before this method exits.The result itself
* is meaningless to Quartz, but may be informative to
* {@link JobListener}s or
* {@link TriggerListener}s that are watching the job's
* execution.
* </p>
*
* @throws JobExecutionException
* if there is an exception while executing the job.
*/
void execute(JobExecutionContext context)
throws JobExecutionException;
}
public class ClosePayJob implements Job{
public void execute(JobExecutionContext context)throws JobExecutionException{
//业务逻辑
}
}3.2 JobDetail
Quartz框架在每次执行Job时,都会重新创建一个Job对象实例,所以它需要Job类的信息以及其他相关信息,以便能够在运行时通过newInstance()的反射机制实例化Job。因此需要通过一个类来描述Job的实现类及其它相关的静态信息,比如Job名字、描述、关联监听器等信息。JobDetail接口包含了能够创建Job类的信息载体,用来保存任务的详细信息。如下代码定义
public interface JobDetail extends Serializable, Cloneable { public JobKey getKey(); /** * * Return the description given to the Job instance by its * creator (if any). *
* * @return null if no description was set. */ public String getDescription(); /** * * Get the instance of Job that will be executed. *
*/ public Class
页:
[1]