Using Spring Boot combined with Quartz can realize task scheduling and scheduled task functions. The following is the process of Spring Boot and Quartz:
pom.xml
Add dependencies: Add Quartz dependencies to the Spring Boot project file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- Create a Job class: Create a
org.quartz.Job
Job class that implements the interface and defines specific task logic.
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 在这里编写具体的任务逻辑
System.out.println("执行定时任务");
}
}
- Create JobDetail: Create an
org.quartz.JobDetail
object to define an instance of Job.
JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
.withIdentity("myJob")
.build();
- Create Trigger: Create an
org.quartz.Trigger
object to define the rules of the trigger.
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger")
.withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) // 每隔5秒执行一次
.build();
- Create SchedulerFactoryBean: Create an
org.springframework.scheduling.quartz.SchedulerFactoryBean
object to configure Quartz's scheduler.
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setTriggers(trigger);
schedulerFactoryBean.setJobDetails(jobDetail);
return schedulerFactoryBean;
}
- Start the application: In the Spring Boot entry class, use
@EnableScheduling
annotations to enable the task scheduling function and run the Spring Boot application.
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- Configure scheduled tasks: Add annotations to methods that require scheduled execution of tasks
@Scheduled
, and specify trigger rules.
@Component
public class MyScheduledTask {
@Scheduled(cron = "0/10 * * * * ?") // 每隔10秒执行一次
public void runTask() {
// 执行定时任务的逻辑
System.out.println("执行定时任务");
}
}
By configuring Job, Trigger and SchedulerFactoryBean, and using @Scheduled
annotations, you can easily implement task scheduling and timed task functions.