作者:Mars酱
声明:本文章由Mars酱原创,部分内容来源于网络,如有疑问请联系本人。
转载:欢迎转载,转载前先请联系我!
前言
前几篇介绍了单体架构的定时任务解决方式,但是现代软件架构由于业务复杂度高,业务的耦合性太强,已经由单体架构拆分成了分布式架构。因此,定时任务的架构也随之修改。而Quartz是分布式定时任务解决方案中使用简单,结构清晰,且不依赖第三方分布式调度中间件的。上车,mars酱带你车里细说~
角色介绍
Quartz入门使用的角色不多,三个角色足够,分别是:
Scheduler:调度器。用来负责任务的调度;
Job:任务。这是一个接口,业务代码继承Job接口并实现它的execute方法,是业务执行的主体部分;
Trigger: 触发器。也是个接口,有两个触发器比较关键,一个是SimpleTrigger,另一个是CronTrigger。前者支持简单的定时,比如:按时、按秒等;后者直接支持cron表达式。下面我们从官方的源代码入手,看看Quartz如何做到分布式的。
官方例子
官方源代码down下来之后,有个examples文件夹:

example1是入门级中最简单的。就两个java文件,一个HelloJob:
package org.quartz.examples.example1;
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());
}
}
另一个SimpleExample:
package org.quartz.examples.example1;
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;
import static org.quartz.DateBuilder.evenMinuteDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
/**
* 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 Excepti

Quartz是一个用于分布式系统的高性能调度框架,通过数据库锁机制保证同一时刻只有一个Scheduler实例访问数据库中的Trigger。文章介绍了Quartz的Job、Trigger和Scheduler的角色,以及如何通过数据库锁实现分布式。Quartz采用悲观锁策略,确保调度线程的互斥访问,提高系统性能和可靠性。

1782

被折叠的 条评论
为什么被折叠?



