一般在项目中,除非定时任务涉及到的业务实在是太简单,使用 @Scheduled 注解来解决定时任务,否则大部分情况可能都是使用 Quartz 来做定时任务。在 Spring Boot 中使用 Quartz ,只需要在创建项目时,添加 Quartz 依赖即可:
项目创建完成后,也需要添加开启定时任务的注解:
@SpringBootApplication
@EnableScheduling
public class QuartzApplication {
public static void main(String[] args) {
SpringApplication.run(QuartzApplication.class, args);
}
}
Quartz 在使用过程中,有两个关键概念,一个是JobDetail(要做的事情),另一个是触发器(什么时候做),要定义 JobDetail,需要先定义 Job,Job 的定义有两种方式:
第一种方式,直接定义一个Bean:
@Component
public class MyJob1 {
public void sayHello() {
System.out.println(“MyJob1>>>”+new Date());
}
}
关于这种定义方式说两点:
-
首先将这个 Job 注册到 Spring 容器中。
-
这种定义方式有一个缺陷,就是无法传参。
第二种定义方式,则是继承 QuartzJobBean 并实现默认的方法:
public class MyJob2 extends QuartzJobBean {
HelloService helloService;
public HelloService getHelloService() {
return helloService;
}
public void setHelloService(HelloService helloService) {
this.helloService = helloService;
}
@Override
protected void executeInternal(JobExecut