Quartz是一个功能丰富的开源作业调度库,几乎可以集成在任何Java应用程序中 - 从最小的独立应用程序到最大的电子商务系统。Quartz可用于创建简单或复杂的计划,以执行数十,数百甚至数万个作业; 将任务定义为标准Java组件的作业,这些组件可以执行几乎任何可以编程的程序。Quartz Scheduler包含许多企业级功能,例如支持JTA事务和集群。springboot在2.x后加入了quartz的支持,可以说真的是这个start还是做的不错的!!
spring定时器
首先呢说一下spring自带的定时器
package com.maoxs.conf;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
@Configurable
@EnableScheduling
public class ScheduledTasks {
@Scheduled(fixedRate = 1000 * 30)
public void reportCurrentTime() {
System.out.println("任务执行 " + dateFormat().format(new Date()));
}
//每1分钟执行一次
@Scheduled(cron = "0 */1 * * * * ")
public void reportCurrentByCron() {
System.out.println("任务执行" + dateFormat().format(new Date()));
}
private SimpleDateFormat dateFormat() {
return new SimpleDateFormat("HH:mm:ss");
}
}
其中呢 @EnableScheduling:标注启动定时任务 @Scheduled(fixedRate = 1000 * 30) 定义某个定时任务。当然也可以使用cron表达式。但是呢需要进行任务的持久和复杂的管控,肯定就不行了,下面上quartz。
quartz
首先呢要使用首先加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
然后在yml中加入
spring:
quartz:
properties:
org:
quartz:
scheduler:
instanceName: MyScheduler
instanceId: AUTO #如果使用集群,instanceId必须唯一,设置成AUTO
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 10
threadPriority: 5
threadsInheritContextClassLoaderOfInitializingThread: true
job-store-type: memory #jdbc 为持久化,memory 为内存
这里呢我封装了一个操作的类
package com.maoxs.conf;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* quartz管理类
*
* @author fulin
*/
@Service
public class QuartzManager {
@Autowired
private Scheduler scheduler;
/**
* 增加一个job
*
* @param jobClass 任务实现类
* @param jobName 任务名称
* @param jobGroupName 任务组名
* @param jobCron cron表达式(如:0/5 * * * * ? )
*/
public void addJob(Class<? extends Job> jobClass, String jobName, String jobGroupName, String jobCron) {
try {
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroupName)
.startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
.withSchedule(CronScheduleBuilder.cronSchedule(jobCron)).startNow().build();
scheduler.scheduleJob(jobDetail, trigger);
if (!scheduler.isShutdown()) {
scheduler.start();
}
} catch