SpringBoot ~ 定时任务Quartz

定时任务Quartz

quartz是一个功能丰富的开源作业调度库

  1. 添加pom依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-quartz</artifactId>
    </dependency>
  2. 创建定时Job

    • 通过普通JavaBean创建,添加@Component注解将之注册到容器
    /**
     * @author wsyjlly
     * @create 2019.07.17 - 14:40
     **/
    @Component
    public class ScheduleDemo2 {
        public void schedule(){
            System.out.println("ScheduleDemo2.schedule...");
        }
    }
    • 通过继承抽象类QuartzJobBean创建,该方式需要实现该类中的executeInternal方法,该方法在任务被调用时使用。
    /**
     * @author wsyjlly
     * @create 2019.07.17 - 14:40
     **/
    public class ScheduleDemo3 extends QuartzJobBean {
        private String name;
        public void setName(String name){
            this.name = name;
        }
    
        @Override
        protected void executeInternal(JobExecutionContext jobExecutionContext){
            System.out.println("ScheduleDemo3.executeInternal..."+name);
        }
    }
    
  3. 创建Quartz配置类QuartzConfig对Job进行配置

    /**
     * @author wsyjlly
     * @create 2019.07.17 - 14:47
     **/
    @Configuration
    public class QuartzConfig {
        
        @Bean
        MethodInvokingJobDetailFactoryBean jobDetail1(){
            MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
            bean.setTargetBeanName("scheduleDemo2");
            bean.setTargetMethod("schedule");
            return bean;
        }
        
        @Bean
        JobDetailFactoryBean jobDetail2(){
            JobDetailFactoryBean bean = new JobDetailFactoryBean();
            bean.setJobClass(ScheduleDemo3.class);
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put("name","ysw");
            bean.setJobDataMap(jobDataMap);
            bean.setDurability(true);
            return bean;
        }
        
        @Bean
        SimpleTriggerFactoryBean simpleTrigger(){
            SimpleTriggerFactoryBean bean = new SimpleTriggerFactoryBean();
            bean.setJobDetail(jobDetail1().getObject());
            bean.setRepeatCount(3);
            bean.setStartDelay(1000);
            bean.setRepeatInterval(2000);
            return bean;
        }
        
        @Bean
        CronTriggerFactoryBean cronTrigger(){
            CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
            bean.setJobDetail(jobDetail2().getObject());
            bean.setCronExpression("* * * * * ?");
            return bean;
        }
    
        @Bean
        SchedulerFactoryBean schedulerFactory(){
            SchedulerFactoryBean bean = new SchedulerFactoryBean();
            SimpleTrigger simpleTrigger = simpleTrigger().getObject();
            CronTrigger cronTrigger = cronTrigger().getObject();
            bean.setTriggers(simpleTrigger,cronTrigger);
            return bean;
        }
    }
上一篇:厘米级实时定位!自动驾驶梦之队跃上云端


下一篇:Docker实战(一)之使用Docker镜像