Quartz具有强大的调度功能、灵活的应用方式和分布式、集群能力,今天我们介绍Quartz定时任务的使用。
Quartz是Job scheduling(作业调度)领域的一个开源项目,Quartz既可以单独使用也可以跟spring框架整合使用,在实际开发中一般会使用后者。使用Quartz可以开发一个或者多个定时任务,每个定时任务可以单独指定执行的时间,例如每隔1小时执行一次、每个月第一天上午10点执行一次、每个月最后一天下午5点执行一次等。
官网:https://www.w3cschool.cn/quartz_doc/
• Scheduler
:任务调度器,所有的任务都是从这里开始。
• Trigger
:触发器,定义任务执行的方式、间隔。
• JobDetail
& Job
: 定义任务具体执行的逻辑。
Scheduler的生命期,从SchedulerFactory
创建它时开始,到Scheduler调用shutdown()
方法时结束;
Scheduler被创建后,可以增加、删除和列举Job和Trigger,以及执行其它与调度相关的操作(如暂停Trigger);
但是,Scheduler只有在调用start()
方法后,才会真正地触发trigger(即执行job)。
导入maven坐标
pom.xml:
<dependencies>
<dependency>
<groupId>org.quartz-schedulergroupId>
<artifactId>quartzartifactId>
<version>2.2.1version>
dependency>
<dependency>
<groupId>org.quartz-schedulergroupId>
<artifactId>quartz-jobsartifactId>
<version>2.2.1version>
dependency>
dependencies>
参考官方文档,创建任务、触发器、调度器等,实现一个定时任务的小例子
package com.quartzlearn.test;
import com.quartzlearn.job.HelloQuartz;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
/**
* @program: quartz_demo
* @description:
* @author: txg
* @create: 2021-10-11 16:25
**/
public class TestJob {
public static void main(String[] args) throws Exception{
//1:任务详情 Job
JobDetail jobDetail = JobBuilder.newJob(HelloQuartz.class)
.usingJobData("name","txg")
.withIdentity("jobname1","jobgroup1")
.build();
//2:触发器 Trigger
//withIntervalInSeconds的参数为间隔时间1s
SimpleTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity("triggername1", "triggergroup1")
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
.build();
//3:调度器 scheduler
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
//4:组合任务和触发器
scheduler.scheduleJob(jobDetail,trigger);
scheduler.start();
//休眠8s
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
scheduler.shutdown();
}
}
该类为具体的任务类,创建一个定时在控制台打印的任务
package com.quartzlearn.job;
/**
* @program: quartz_demo
* @description: 具体任务类
* @author: txg
* @create: 2021-10-11 16:24
**/
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;
/**
* 具体任务类:
* 例如:定时清理图片,清理数据库表临时数据等,一般为周期性执行
*/
public class HelloQuartz implements Job{
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
Object name = context.getJobDetail().getJobDataMap().get("name");
System.out.println("name = " + name);
System.out.println("time = " + new Date());
}
}
该例子的意思是,每隔1s,执行HelloQuartz定时任务,执行8s后休眠,那么一共将在控制台打印1+8=9次。
项目目录结构:
打包方式为war,并导入Quartz和spring相关坐标
pom.xml:
<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.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>quartz_demoartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.quartz-schedulergroupId>
<artifactId>quartzartifactId>
<version>2.2.1version>
dependency>
<dependency>
<groupId>org.quartz-schedulergroupId>
<artifactId>quartz-jobsartifactId>
<version>2.2.1version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<configuration>
<port>8080port>
<path>/path>
configuration>
plugin>
plugins>
build>
project>
类名方法名自己定义,可以后面的配置文件中配置对应的方法
package com.quartzlearn.job;
import java.util.Date;
/**
* @program: quartz_demo
* @description: 任务类
* @author: txg
* @create: 2021-10-11 17:29
**/
public class JobDemo {
public void run(){
System.out.println("time"+new Date());
}
}
配置文件:application-jobs.xml;
配置自定义Job、任务描述、触发器、调度工厂等
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="jobDemo" class="com.quartzlearn.job.JobDemo">bean>
<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="jobDemo">property>
<property name="targetMethod" value="run">property>
bean>
<bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail">property>
<property name="cronExpression">
<value>0/10 * * * * ? *value>
property>
bean>
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<ref bean="trigger">ref>
property>
bean>
beans>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:application-jobs.xmlparam-value>
context-param>
web-app>
每10s将执行一次run方法,执行程序结果如下:
以上就是搭建定时任务quartz框架的案例,和quartz整合spring的案例!
感谢你的支持~