1.引入Quartz依赖
2.SpringBoot启动类增加@EnableScheduling注解
3.创建一个定时任务工作类在方法,代码如下:
package com.jlzh.lftwebservice.service.quartz;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @ClassName: QuartzJob
* @ Description: 定时任务类
* @author:
* @date:2022/11/02
*/
@Component
public class QuartzJob{
@Scheduled(cron = "0/5 * * * * ? ")
protected void executeInternal() throws JobExecutionException {
String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
System.out.println(time + "===> 正在工作。。。");
}
}
此时要注意的是定时任务所在的类要交给Spring容器管理,最简单的就是在类上增加@Component注释。定时任务工作方法上增加@Scheduled(cron = "0/5 * * * * ? ")注释表示任务每5秒执行一次。
4.执行结果如截图所示:
5.cron的值也可以通过外部配置文件的形式指定,代码如下:
package com.jlzh.lftwebservice.service.quartz;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @ClassName: QuartzJob
* @ Description: 定时任务类
* @author:
* @date:2022/11/02
*/
@Component
public class QuartzJob{
@Scheduled(cron = "${cron.exp}")
protected void executeInternal() throws JobExecutionException {
String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
System.out.println(time + "===> 正在工作。。。");
}
}
然后在在配置文件application.yml中填写配置变量的值,此种方式比较灵活,不用修改代码即可更改时间。而且如果将值改为"-“,代表定时任务无效。
值改为”-”后代表定时任务无效,直接使用"-”会标红,可以那单引号引一下即可