springboot整合quartz简单示例

1. 什么是quartz

什么是quartz
参考链接 https://baike.baidu.com/item/quartz/3643055

2. quartz组成

  1. Job: 任务 (定义我要做什么)
  2. Trigger 调度规则(定义什么时候做)
  3. Scheduler 调度器(按照调度规则执行任务)

3. 示例代码

导入springbootQuartz依赖坐标

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

springboot启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling   // <-----启用Spring的计划任务执行能力
public class QuartzdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(QuartzdemoApplication.class, args);
    }
}

MyQuartzJob.java

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Date;

/**
 * @Author: guohui.wang
 * @Date: 2020-11-03 11:29
 * @implements: org.quartz.Job
 * @desc: 调度任务类,实现Job接口,实现execute方法,定义任务内容
 */
public class MyQuartzJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("executing..." + new Date());
    }
}

MyQuartzConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * @Author: guohui.wang
 * @Date: 2020-11-03 11:30
 * @desc: quartz配置类,在此处配置任务、调度规则、调度器。
 */
@Configuration
public class MyQuartzConfig {
    @Bean
    public JobDetailFactoryBean getJobDetailFactoryBean() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(MyQuartzJob.class); // 设置任务调度类(Job的实现类)
        return factoryBean;
    }

    @Bean
    public CronTriggerFactoryBean getCronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean) {
        CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
        factoryBean.setJobDetail(jobDetailFactoryBean.getObject()); // 将任务注入到调度规则中
        factoryBean.setCronExpression("* * * * * ?"); // 使用cron表达式设置调度规则
        return factoryBean;
    }

    @Bean
    public SchedulerFactoryBean getSchedulerFactoryBean(CronTriggerFactoryBean cronTriggerFactoryBean) {
        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        factoryBean.setTriggers(cronTriggerFactoryBean.getObject()); // 将调度规则注入到调度器中调度
        return factoryBean;
    }
}

4. 执行结果

执行结果

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 点我我会动 设计师:白松林 返回首页