要使用Spring Quartz,您需要遵循以下步骤:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 在这里编写要执行的任务逻辑
}
}
@Configuration
public class QuartzConfig {
@Bean
public JobDetail myJobDetail() {
return JobBuilder.newJob(MyJob.class)
.withIdentity("myJob")
.storeDurably()
.build();
}
@Bean
public Trigger myJobTrigger() {
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10)
.repeatForever();
return TriggerBuilder.newTrigger()
.forJob(myJobDetail())
.withIdentity("myJobTrigger")
.withSchedule(scheduleBuilder)
.build();
}
}
在这个配置类中,我们创建了一个JobDetail和一个Trigger,定义了任务的调度规则。
@EnableScheduling
注解,以启用任务调度功能。@SpringBootApplication
@EnableScheduling
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
这是使用Spring Quartz的基本步骤。您可以根据需要进一步配置Quartz调度器和任务。有关更多信息,请参阅Spring Quartz文档。