Quartz is a richly featured, open source job scheduling library that can be integrated within virtually any Java application。

前言

当定时任务愈加复杂时,使用Spring注解@Schedule 已经不能满足业务需要。
@Schedule实现的定时任务:

  • 不能动态管理任务;
  • Job信息不能持久化到数据库;
  • Job执行失败的时候不能保持数据一致性;
  • 不支持集群分布式部署。

Quartz能够完全满足上述需求,而且还支持开源。Quartz是一个功能丰富的开源作业调度库,可以集成到几乎任何Java应用程序中。

集成

Spring Boot 对集成Quartz提供了很好的支持,只需要在pom文件中添加以下依赖即可。

<!--quartz--><!-- 该依赖必加,里面有spring对schedule的支持 --><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>4.1.6.RELEASE</version></dependency><dependency><groupId>org.quartz-scheduler</groupId><artifactId>quartz-jobs</artifactId><version>2.2.1</version></dependency><dependency><groupId>org.quartz-scheduler</groupId><artifactId>quartz</artifactId><version>2.2.1</version></dependency>

代码实现

完整实现如下:

//定义一个Job,必须实现org.quartz.Job 接口
public class JobTest implements Job {@Overridepublic void execute(JobExecutionContext context) throws JobExecutionException {System.out.println("This is a test!!!" + new Date());}public static void main(String[] args) {try {//1.实例化并开始一个调度器Schedule// Grab the Scheduler instance from the FactoryScheduler scheduler = StdSchedulerFactory.getDefaultScheduler();// and start it offscheduler.start();//2.添加触发器// define the job and tie it to our MyJob classJobDetail jobDetail = newJob(JobTest.class).withIdentity("job1", "group1").build();// Trigger the job to run now, and then repeat every 40 seconds foreverTrigger trigger = newTrigger().withIdentity("trigger1", "group1").startNow().withSchedule(simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();// Tell quartz to schedule the job using our triggerscheduler.scheduleJob(jobDetail, trigger);} catch (SchedulerException e) {e.printStackTrace();}}
}

结果

Spring Boot 定时任务之Quartz_Java

参照

quartz-scheduler