Quartz-定时任务框架
引言
Quartz是一个定时任务调度框架,可以解决以下问题:
- 想在15分钟后,查看订单是否支付,未支付则取消订单
- 想每个月30号,信用卡自动还款
- 想在某个时间点做某件事情
Quartz是要做定时任务的调度,设置好触发的时间规则,以及相应的任务即可
Quartz使用
导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>quartz01</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<!--Quartz任务调度-->
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
定义job
HelloJob
public class HelloJob implements Job{
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//创建工作详情
JobDetail jobDetail = jobExecutionContext.getJobDetail();
//获取工作名称
JobKey key = jobDetail.getKey();
System.out.println(key.getName());
System.out.println(key.getGroup());
System.out.println("hello quartz!!!!"+new Date());
}
}
API测试
public class HelloQuartz {
public static void main(String[] args) throws SchedulerException {
//1.创建调度器Scheduler
Scheduler defaultScheduler = new StdSchedulerFactory().getDefaultScheduler();
//2.触发器
SimpleTrigger trigger= TriggerBuilder.newTrigger().withIdentity("trigger1","group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever())
.endAt(new GregorianCalendar(2020,10,31,12,10,30).getTime())
.build();
//3.Jobdetail
JobDetail build = JobBuilder.newJob(HelloJob.class).withIdentity("job1","group1").build();
//4.将Jobdetail和触发器加入到调度器
defaultScheduler.scheduleJob(build,trigger);
//5.开启工作
defaultScheduler.start();
}
}
配置
默认情况下,Quartz会加载classpath下的”quartz.properties”文件作为配置属性,如果找不到则会使用quartz框架自己jar下org/quartz包底下的”quartz.properties”文件。
# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
org.quartz.jobStore.misfireThreshold: 60000
org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
核心类说明
- Sceduler:调度器。所有的调度都是由它控制的,是Quartz的大脑,所有任务都是由它来管理
- Job:任务,想定时执行的事情
- JobDetail:基于Job进一步封装,其中关联一个job,为其指定更详细的属性,比如标识
- Trigger:触发器。可以给指定任务,指定触发机制。
Trigger
1.SimpleTrigger
- 在一定的时间间隔(单位毫秒)执行任务
- 指定起始和截止时间
- 指定时间间隔,执行次数
//2.触发器
SimpleTrigger trigger= TriggerBuilder.newTrigger().withIdentity("trigger1","group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever())
.endAt(new GregorianCalendar(2020,10,31,12,10,30).getTime())
.build();
2.CronTrigger(重点)
- 适合更复杂的任务,它支持类型于Linux Cron语法(并且更强大)
- 指定Cron表达式即可
public class CronQuartz {
public static void main(String[] args) throws SchedulerException {
//1.创建调度器Scheduler
Scheduler defaultScheduler = new StdSchedulerFactory().getDefaultScheduler();
//2.触发器
CronTrigger build1 = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("*/3 * * 31 10 ?"))
.build();
//3.Jobdetail
JobDetail build = JobBuilder.newJob(HelloJob.class).withIdentity("job1","group1").build();
//4.将Jobdetail和触发器加入到调度器
defaultScheduler.scheduleJob(build,build1);
//5.开启工作
defaultScheduler.start();
}
}
2.1Cron表达式组成
- 表达式组成:“秒 分 时 日 月 星期几[年]”,其中“年”是可选的,一般不指定
2.2Cron表达式符号
-
“?”字符:表示不确定的值
-
“,”字符:指定数个值
-
“-”字符:指定一个值的范围
-
“/”字符:指定一个值的增加幅度。n/m表示从n开始,每次增加m
-
“L”字符:用在日表示一个月中的最后一天,用在周表示该月最后一个星期X
-
“W”字符:指定离给定日期最近的工作日(周一到周五)
-
“#”字符:表示该月第几个周X。6#3表示该月第3个周五
2.3Cron表
-
每隔5秒执行一次:*/5 * * * * ?
-
每隔1分钟执行一次:0 */1 * * * ?
-
每天23点执行一次:0 0 23 * * ?
-
每天凌晨1点执行一次:0 0 1 * * ?
-
每月1号凌晨1点执行一次:0 0 1 1 * ?
-
每月最后一天23点执行一次:0 0 23 L * ?
-
每周星期天凌晨1点实行一次:0 0 1 ? * L
-
在26分、29分、33分执行一次:0 26,29,33 * * * ?
-
每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?
Spring整合Quartz(重点)
1.导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>quartz01</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<!--Quartz任务调度-->
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
2.定义job
HelloJob
public class HelloJob implements Job{
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//创建工作详情
JobDetail jobDetail = jobExecutionContext.getJobDetail();
JobKey key = jobDetail.getKey();
System.out.println(key.getName());
System.out.println(key.getGroup());
System.out.println("hello quartz!!!!"+new Date());
}
}
3.配置
- 调度器:SchedulerFactoryBean
- 触发器:CronTriggerFactoryBean
- JobDetail:JobDetailFactoryBean
4.操作
4.1 启动任务
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--Spring整合Quartz进行配置遵循以下的步骤
1.定义工作任务的job
2.定义触发器Trigger,并将触发器和工作任务绑定e
3.定义调度器,并将Trigger注册到Scheduler
-->
<bean id="jobDetailFactoryBean" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="cn.ozl.job.HelloJob"></property>
<property name="name" value="job1"></property>
<property name="group" value="group1"></property>
</bean>
<bean id="cronTriggerFactoryBean" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="name" value="trigger1"></property>
<property name="group" value="group1"></property>
<property name="jobDetail" ref="jobDetailFactoryBean"></property>
<property name="cronExpression" value="* * * * * ?"></property>
</bean>
<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTriggerFactoryBean"></ref>
</list>
</property>
<property name="configLocation" value="classpath:quartz.properties"></property>
</bean>
</beans>
启动任务
ApplicationContext Context = new ClassPathXmlApplicationContext("applicationContext.xml");
4.2 任务操作
4.2.1 删除任务
public class QuartzTest {
public static void main(String[] args) throws InterruptedException, SchedulerException {
ApplicationContext Context = new ClassPathXmlApplicationContext("applicationContext.xml");
Thread.sleep(5000);
StdScheduler scheduler =(StdScheduler)Context.getBean("schedulerFactoryBean");
//任务删除
scheduler.deleteJob(JobKey.jobKey("job1","group1"));
}
}
4.2.2 暂停,恢复
scheduler.pauseJob(JobKey.jobKey("job1","group1"));
System.out.println("================");
scheduler.resumeJob(JobKey.jobKey("job1","group1"));
4.2.3 批量操作
scheduler.pauseJobs(GroupMatcher.<JobKey>groupEquals("group1"));
System.out.println("================");
scheduler.resumeJobs(GroupMatcher.<JobKey>groupEquals("group1"));