Quartz概念性内容:
Scheduler:调度任务的主要API
SchedulerBuilder:构建Scheduler
Job:调度任务执行的接口,即定时任务执行的方法
JobDetail:定时任务的实例
JobBuilder:构建JobDetail
Trigger:定时执行的组件
TriggerBuiler:构建Trigger
导入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
定义所要执行的定时任务:
public class Job1 extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
//简单输出日期
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Job1----" + sdf.format(new Date()));
}
}
创建定时任务的配置对象,关联定时任务:
@Configuration
public class QuartzConfig {
@Bean
public JobDetail jobDetail1(){
//关联job对象
return JobBuilder.newJob(Job1.class).storeDurably().build();
}
@Bean
public Trigger trigger1(){
//设置job1的一个执行规则
SimpleScheduleBuilder scheduleBuilder =SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10) //每十秒执行一次
.repeatForever(); //永久重复,一直执行下去
return TriggerBuilder.newTrigger()
.forJob(jobDetail1())
.withSchedule(scheduleBuilder)
.build();
}
}
SimpleScheduleBuilder相关API详解:http://www.quartz-scheduler.org/api/2.1.7/org/quartz/SimpleScheduleBuilder.html
运行效果: