springboot quartz的实现代码
时间: 2023-07-23 19:26:05 浏览: 97
springboot+Quartz实现任务调度的示例代码
以下是一个简单的 Spring Boot 集成 Quartz 的实现代码:
1. 添加 Maven 依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
```
2. 创建 Quartz 配置类
```java
@Configuration
public class QuartzConfig {
@Bean
public JobDetail sampleJobDetail() {
return JobBuilder.newJob(SampleJob.class).withIdentity("sampleJob")
.usingJobData("name", "World").storeDurably().build();
}
@Bean
public Trigger sampleJobTrigger() {
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10).repeatForever();
return TriggerBuilder.newTrigger().forJob(sampleJobDetail())
.withIdentity("sampleTrigger").withSchedule(scheduleBuilder).build();
}
}
```
3. 创建 Quartz Job 类
```java
@Component
public class SampleJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
String name = context.getJobDetail().getJobDataMap().getString("name");
System.out.println("Hello " + name + "!");
}
}
```
4. 运行定时任务
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Autowired
private Scheduler scheduler;
@Autowired
private Trigger sampleJobTrigger;
@Autowired
private JobDetail sampleJobDetail;
@PostConstruct
public void init() {
try {
scheduler.scheduleJob(sampleJobDetail, sampleJobTrigger);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
```
这样就可以实现一个简单的 Spring Boot 集成 Quartz 的定时任务了。
阅读全文