官网:http://www.quartz-scheduler.org/
1)job - 任务 - 你要做什么事?
2)Trigger - 触发器 - 做什么事,什么时候触发,可以传入任务
3)Scheduler - 任务调度 - 可以传入多个触发器进行任务调度
SpringBoot整合Quartz框架
添加Quartz依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- 自定义一个Job
package com.by.quartz;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class QuartzDemo {
//任务
public void printTime(){
System.out.println("现在时刻:"+new Date());
}
}
- 编写quartz配置类
package com.by.config;
import com.by.quartz.QuartzDemo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
@Configuration
public class QuartzConfig {
@Bean //job:干什么事
public MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean(QuartzDemo quartzDemo){
MethodInvokingJobDetailFactoryBean JobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean();
JobDetailFactoryBean.setTargetObject(quartzDemo);
JobDetailFactoryBean.setTargetMethod("printTime");
return JobDetailFactoryBean;
}
@Bean //trigger:什么时候干什么事
public CronTriggerFactoryBean cronTriggerFactoryBean(MethodInvokingJobDetailFactoryBean JobDetailFactoryBean){
CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
cronTriggerFactoryBean.setCronExpression("0/5 * * * * ?");
cronTriggerFactoryBean.setJobDetail(JobDetailFactoryBean.getObject());
return cronTriggerFactoryBean;
}
@Bean //scheduler:调度
public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean cronTriggerFactoryBean){
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setTriggers(cronTriggerFactoryBean.getObject());
return schedulerFactoryBean;
}
}
- 启动启动类
package com.by;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.by.mapper")
public class IcanBackendApp {
public static void main(String[] args) {
SpringApplication.run(IcanBackendApp.class,args);
}
}
结果 :运行启动类,观察控制台,可以发现每隔5秒会输出一次,说明每隔1秒自定义 Job被调用一次。