目录
4.1 在SpringBoot的启动类类中加⼊ @EnableScheduling 注解,启⽤定时任务的配置
5.2 在SpringBoot的启动类类中加⼊ @EnableScheduling 注解,启⽤定时任务的配置
前言:
Quartz 任务存储方式
内存方式(RAMJobStore):将任务临时存储到内存中,仅支持单项目部署,项目重启后任务会失效,不 支持由调度器控制任务漂移,不建议使用。
数据库方式(JDBCJobStore): Quartz提供了多种数据库的所需表结构脚本,它内部通过 DataSource来 操作数据,支持分布式方式部署、支持任务漂移,项目重启后任务不会丢失,直到任务执行完成后才会 被从数据库内清除。
1. Quartz 是一个什么东西?
- 定时任务
2. Quartz 到底是干什么用的?
使用定时任务的情况:
每周末凌晨备份数据
触发条件 5 分钟后发送邮件通知
30 分钟未支付取消订单
每 1 小时去拉取数据
3. cron表达式
{Seconds} {Minutes} {Hours} {DayofMonth} {Month} {DayofWeek} {Year} {Seconds} {Minutes} {Hours} {DayofMonth} {Month} {DayofWeek}
每个域都可以用数字表示,还可以出现如下特殊字符
* : 表示匹配该域的任意值,比如Minutes域使用*,就表示每分钟都会触发
- : 表示范围,比如Minutes域使用10-20,就表示从10分钟到20分钟每分钟都会触发一次
, : 表示列出枚举值,比如Minutes域使用1,3.就表示1分钟和3分钟都会触发一次
/ : 表示间隔时间触发(开始时间/时间间隔),例如在Minutes域使用 5/10,就表示从第5分钟开始,每隔10 分钟触发一次
? : 表示不指定值,简单理解就是忽略该字段的值,直接根据另一个字段的值触发执行
# : 表示该月第n个星期x(x#n),仅用星期域,如:星期:6#3,表示该月的第三个星期五
L : 表示最后,是单词"last"的缩写(最后一天或最后一个星期几);仅出现在日和星期的域中,用在日则表 示该月的最后一天,用在星期则表示该月的最后一个星期,如:星期域上的值为5L,则表示该月最后一个星期的 星期四,在使用'L'时,不要指定列表','或范围'-',否则易导致出现意料之外的结果
W: 仅用在日的域中,表示距离当月给定日期最近的工作日(周一到周五),是单词"weekday"的缩写
4. spring 自带的定时任务操作
4.1 在SpringBoot的启动类类中加⼊ @EnableScheduling 注解,启⽤定时任务的配置
package com.jmh.quartz;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class QuartzApplication {
public static void main(String[] args) {
SpringApplication.run(QuartzApplication.class, args);
}
}
4.2 创建定时任务实现类
package com.jmh.quartz.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* @author 蒋明辉
* @data 2022/10/29 15:11
*/
@Component
@Slf4j
public class Task {
@Scheduled(fixedRate = 10000)
public void work() {
log.warn("现在时间:" + LocalDateTime.now());
}
}
Scheduled参数
@Scheduled(fixedRate=5000):上⼀次开始执⾏时间点之后5秒再执⾏
@Scheduled(fixedDelay=5000):上⼀次执⾏完毕时间点之后5秒再执⾏
@Scheduled(initialDelay=1000, fixedRate=5000):第⼀次延迟1秒后执⾏,之后按fixedRate的规则 每5秒执⾏⼀次
@Scheduled(cron="*/5 * * * * *"):通过cron表达式定义规则
第三篇章可使用cron表达式
使用junit测试
@Test
public void Test(){
while (true){
}
}
5. Quartz 定时任务的使用与操作
任务存储方式:内存方式
5.1 导入pom依赖
<!--quartz定时任务依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
5.2 在SpringBoot的启动类类中加⼊ @EnableScheduling 注解,启⽤定时任务的配置
package com.jmh.quartz;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class QuartzApplication {
public static void main(String[] args) {
SpringApplication.run(QuartzApplication.class, args);
}
}
5.3 创建Job 定时任务
任务是一个实现 org.quartz.Job 接口的类,任务类必须含有空构造器 当关联这个任务实例的触发器表明的执行时间到了的时候,调度程序 Scheduler 会调用这个方法来执行 任务,任务内容就可以在这个方法中执行
package com.jmh.quartz.utils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* @author 蒋明辉
* @data 2022/10/29 19:47
*/
@Slf4j
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
System.out.println(jobDataMap.get("name")+"正在"+jobDataMap.get("loc")+"努力打扫卫生");
}
}
5.4 完整实例化的过程
在junit 里面操作
package com.jmh.quartz;
import com.jmh.quartz.model.Book;
import com.jmh.quartz.model.Price;
import com.jmh.quartz.service.IBookService;
import com.jmh.quartz.service.IPriceService;
import com.jmh.quartz.utils.MyJob;
import org.junit.jupiter.api.Test;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.xml.validation.SchemaFactory;
import java.math.BigDecimal;
import java.util.Date;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
@SpringBootTest
class QuartzApplicationTests {
@Test
void contextLoads() throws SchedulerException {
//1.创建调度器工厂
SchedulerFactory factory = new StdSchedulerFactory();
//2.得到调度器
Scheduler scheduler = factory.getScheduler();
//3.创建任务
//3.1 job是模板 jobDetail是实例
JobDetail jobDetail=newJob(MyJob.class)
.withDescription("公司搞大扫除")//描述
.withIdentity("a","b")//任务编号
.build()
;
//带数据的方式
//实例2
jobDetail.getJobDataMap().put("name","张三");
jobDetail.getJobDataMap().put("loc","男厕所");
JobDetail jobDetail02=newJob(MyJob.class)
.withDescription("公司搞大扫除")//描述
.withIdentity("b","c")//任务编号
.usingJobData("name","李四")//带数据过去
.build()
;
//4.创建触发器
Trigger trigger = TriggerBuilder.newTrigger()
.withDescription("大扫除触发器")
.withIdentity("b", "c")
//1.使用简单的触发器
//.startAt(new Date())
/*.withSchedule(
simpleSchedule()
.withIntervalInSeconds(1)
.withRepeatCount(10) //SimpleTrigger.REPEAT_INDEFINITELY
)*/
//2.使用cron表达式
.withSchedule(CronScheduleBuilder.cronSchedule("* * * * * ?"))
.build();
//5.将触发器和任务绑定到调度器里
scheduler.scheduleJob(jobDetail,trigger);
//6.启动调度器
scheduler.start();
while (true){
//我要休息了
//睡觉睡觉 我要睡觉觉
//再见 !我们明天见
//我最爱的java 和我最爱的idea
//希望睡一觉就能把我的这万恶不赦的强迫症给搞没吧
//求求你啦 我的上帝你是我的神
}
}
}