springboot integrates quartz process

Using Spring Boot combined with Quartz can realize task scheduling and scheduled task functions. The following is the process of Spring Boot and Quartz:

  1. pom.xmlAdd dependencies: Add Quartz dependencies to the Spring Boot project file.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
  1. Create a Job class: Create a org.quartz.JobJob 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("执行定时任务");
    }
}
  1. Create JobDetail: Create an org.quartz.JobDetailobject to define an instance of Job.
JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
    .withIdentity("myJob")
    .build();
  1. Create Trigger: Create an org.quartz.Triggerobject to define the rules of the trigger.
Trigger trigger = TriggerBuilder.newTrigger()
    .withIdentity("myTrigger")
    .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) // 每隔5秒执行一次
    .build();
  1. Create SchedulerFactoryBean: Create an org.springframework.scheduling.quartz.SchedulerFactoryBeanobject to configure Quartz's scheduler.
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
    
    
    SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
    schedulerFactoryBean.setTriggers(trigger);
    schedulerFactoryBean.setJobDetails(jobDetail);
    return schedulerFactoryBean;
}
  1. Start the application: In the Spring Boot entry class, use @EnableSchedulingannotations 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);
    }
}
  1. 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 @Scheduledannotations, you can easily implement task scheduling and timed task functions.

Guess you like

Origin blog.csdn.net/kkwyting/article/details/133494606