第一步:开启定时任务,在启动类上添加 @EnableScheduling 注解
@SpringBootApplication
@EnableScheduling // 开启定时任务
public class SpringBootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootTaskApplication.class, args);
}
}
第二步:通过注解设定定时任务
新建类,添加 @Component 注解注册 Spring 组件,定时任务方法需要在 Spring 组件类才能生效。
在类中方法添加了 @Scheduled 注解,所以会按照 @Scheduled 注解参数指定的规则定时执行。
/**
* 任务类
*/
@Component
public class MySpringTask {
/**
* 每2秒执行1次
*/
@Scheduled(fixedRate = 2000)
public void fixedRateMethod() throws InterruptedException {
System.out.println("fixedRateMethod:" + new Date());
Thread.sleep(1000);
}
}
@Scheduled 也支持使用 Cron 表达式, Cron 表达式可以非常灵活地设置定时任务的执行时间。其从左到右一共 6 个位置,分别表示:
秒(0~59) 例如0/5表示每5秒
分(0~59)
时(0~23)
日(0~31)的某天,需计算
月(0~11)
周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
其规范为:
// Cron表达式范例:
每隔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 * * ?
对于定时任务举例为:
/**
* 任务类
*/
@Component
public class MySpringTask {
/**
* 在每分钟的00秒执行
*/
@Scheduled(cron = "0 * * * * ?")
public void jump() throws InterruptedException {
System.out.println("心跳检测:" + new Date());
}
/**
* 在每天的00:00:00执行
*/
@Scheduled(cron = "0 0 0 * * ?")
public void stock() throws InterruptedException {
System.out.println("置满库存:" + new Date());
}
}
第一步:引入依赖
<!-- Quartz -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
第二步:开启定时任务, 在启动类上添加 @EnableScheduling 注解
@SpringBootApplication
@EnableScheduling // 开启定时任务
public class SpringBootQuartzApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootQuartzApplication.class, args);
}
}
第三步:Quartz 定时任务开发
Quartz 定时任务需要通过 Job 、 Trigger 、 JobDetail 来设置。
Job :具体任务操作类
Trigger :触发器,设定执行任务的时间
JobDetail :指定触发器执行的具体任务类及方法
首先写一个Job组件:
/**
* 打折任务
*/
@Component // 注册到容器中
public class DiscountJob {
/**
* 执行打折
*/
public void execute() {
System.out.println("更新数据库中商品价格,统一打5折");
}
}
然后在配置类中设定 Trigger 及 JobDetail :
/**
* 定时任务配置
*/
@Configuration
public class QuartzConfig {
/**
* 配置JobDetail工厂组件,生成的JobDetail指向discountJob的execute()方法,所以每周六的 8 点,就会运行 discountJob 组件的 execute () 方法 1 次;
*/
@Bean
MethodInvokingJobDetailFactoryBean jobFactoryBean() {
MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
bean.setTargetBeanName("discountJob");
bean.setTargetMethod("execute");
return bean;
}
/**
* 触发器工厂
*/
@Bean
CronTriggerFactoryBean cronTrigger() {
CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
// Corn表达式设定执行时间规则 每周六的 08:00:00 执行 1 次
bean.setCronExpression("0 0 8 ? * 7");
// 执行JobDetail
bean.setJobDetail(jobFactoryBean().getObject());
return bean;
}
}