springboot整合spring-boot-starter-quartz是实现cron定时任务的详细步骤及代码案例
时间: 2024-01-24 15:03:45 浏览: 112
Spring Boot整合Quartz实现cron定时任务的步骤如下:
1.在pom.xml中添加依赖
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
```
2.创建Job类
```
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 这里编写具体的定时任务
}
}
```
3.创建JobDetail和Trigger
```
@Configuration
public class QuartzConfig {
@Bean
public JobDetail myJobDetail() {
return JobBuilder.newJob(MyJob.class).withIdentity("myJob").storeDurably().build();
}
@Bean
public Trigger myTrigger() {
return TriggerBuilder.newTrigger().forJob(myJobDetail())
.withIdentity("myTrigger").withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 * * ?")).build();
}
}
```
4.启动定时任务
```
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Autowired
private Scheduler scheduler;
@Autowired
private Trigger myTrigger;
@Autowired
private JobDetail myJobDetail;
@PostConstruct
public void start() throws SchedulerException {
scheduler.scheduleJob(myJobDetail, myTrigger);
}
}
```
这里的注解`@PostConstruct`表示在Bean初始化之后执行该方法。
5.编写具体的定时任务逻辑
```
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("定时任务执行了!");
}
}
```
完整的代码示例:
```
// MyJob.java
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("定时任务执行了!");
}
}
// QuartzConfig.java
@Configuration
public class QuartzConfig {
@Bean
public JobDetail myJobDetail() {
return JobBuilder.newJob(MyJob.class).withIdentity("myJob").storeDurably().build();
}
@Bean
public Trigger myTrigger() {
return TriggerBuilder.newTrigger().forJob(myJobDetail())
.withIdentity("myTrigger").withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 * * ?")).build();
}
}
// Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Autowired
private Scheduler scheduler;
@Autowired
private Trigger myTrigger;
@Autowired
private JobDetail myJobDetail;
@PostConstruct
public void start() throws SchedulerException {
scheduler.scheduleJob(myJobDetail, myTrigger);
}
}
```
这里的定时任务是每天凌晨0点执行一次,并打印一句话。
阅读全文