Quartz教程
** 1.导入依赖**
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
2.配置类
package com.example.demoz.config;
import com.example.demoz.job.MyJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QuartzConfig {
@Bean
public JobDetail quartzTestDetail() {
JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
//添加认证信息
.withIdentity("jobDetail", "quarts")
.storeDurably(true)
.build();
return jobDetail;
}
/**
* 创建触发器
*/
@Bean
public Trigger quartzTestJobTrigger() {
//执行频率
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("*/5 * * * * ?");
//创建触发器
Trigger trigger = TriggerBuilder.newTrigger()
.forJob(quartzTestDetail())
.startNow()
//添加认证信息
.withIdentity("jobTrigger", "trigger")
//添加执行规则
.withSchedule(cronScheduleBuilder)
.build();
return trigger;
}
}
3.job实现
package com.example.demoz.job;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class MyJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println("执行定时任务");
}
}