• Springboot手动添加quartz-jobs


    添加pom文件

     <!-- quartz 模块 -->
            <dependency>
                <groupId>org.quartz-scheduler</groupId>
                <artifactId>quartz</artifactId>
                <version>2.3.0</version>
                <exclusions>
                    <exclusion>
                        <groupId>ch.qos.logback</groupId>
                        <artifactId>logback-classic</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>ch.qos.logback</groupId>
                        <artifactId>logback-core</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.quartz-scheduler</groupId>
                <artifactId>quartz-jobs</artifactId>
                <version>2.3.0</version>
            </dependency>
    

    配置QuartzConfig

    import org.quartz.Scheduler;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    import org.springframework.scheduling.quartz.SchedulerFactoryBean;
    import java.util.concurrent.ThreadPoolExecutor;
    
    @Configuration
    public class QuartzConfig {
    
        @Autowired
        private QuartzJobFactory quartzJobFactory;
    
        @Bean(name = "scheduler")
        public Scheduler scheduler() throws Exception {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(5);
            executor.setMaxPoolSize(10);
            executor.setQueueCapacity(200);
            executor.setThreadNamePrefix("scheduler_Executor");
            // rejection-policy:当pool已经达到max size的时候,如何处理新任务
            // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            executor.initialize();
    
            SchedulerFactoryBean factoryBean=new SchedulerFactoryBean();
            factoryBean.setJobFactory(quartzJobFactory);
            factoryBean.setTaskExecutor(executor);
            factoryBean.afterPropertiesSet();
            Scheduler scheduler=factoryBean.getScheduler();
            scheduler.start();
            return scheduler;
        }
    }
    

    配置QuartzJobFactory

    import org.quartz.spi.TriggerFiredBundle;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
    import org.springframework.scheduling.quartz.AdaptableJobFactory;
    import org.springframework.stereotype.Component;
    
    @Component
    public class QuartzJobFactory extends AdaptableJobFactory {
        //这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.
        @Autowired
        private AutowireCapableBeanFactory capableBeanFactory;
    
        public Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
            //调用父类的方法
            Object jobInstance = super.createJobInstance(bundle);
            //进行注入,这属于Spring的技术,不清楚的可以查看Spring的API.
            capableBeanFactory.autowireBean(jobInstance);
            return jobInstance;
        }
    }
    
    import org.quartz.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.context.support.SpringBeanAutowiringSupport;
    
    import java.util.Date;
    @DisallowConcurrentExecution
    public class JobWx implements Job {
        private Logger log= LoggerFactory.getLogger(JobWx.class);
    
        @Autowired
        private CdpWxService cdpWxService;
    
        @Override
        public void execute(JobExecutionContext jobExecutionContext) {
            System.out.println("Wx " + new Date() + jobExecutionContext);
            log.info("*****************************************{},{}" ,new Date() , jobExecutionContext);
            JobDataMap j = jobExecutionContext.getJobDetail().getJobDataMap();
            log.info("*****************************************{}" ,jobExecutionContext.getJobDetail());
            log.info("*****************************************{}" ,j);
            Scheduler scheduler = jobExecutionContext.getScheduler();
            try {
                String orderNo = String.valueOf(j.get("orderNo"));
                //TODO 修改成查询
                if(!"null".equals(orderNo)){
                    Result r =cdpWxService.selectOrder(orderNo);
                    if(r.isSuc()){
                        System.out.println(scheduler.deleteJob(JobKey.jobKey(orderNo, Constant.JOB_GROUP_3)));
                    }
                }
            } catch (Exception e) {
                log.error("job is error : {}",e);
                e.printStackTrace();
            }
        }
    
        protected void springBeanAutowiringSupport() {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        }
    
    }
    

    业务逻辑

    @Autowired
     private Scheduler scheduler;
    
    
    
    public void addJob(String cusNo) throws SchedulerException {
            JobDetail jobDetail = newJob(JobWx.class).withIdentity(cusNo, Constant.JOB_GROUP_3).build();
            // Trigger the job to run now, and then repeat every 40 seconds forever
            jobDetail.getJobDataMap().put("orderNo", cusNo);
            Trigger trigger =
                    newTrigger().withIdentity("wxst" + cusNo, Constant.JOB_GROUP_1).startAt(DateUtil.setSendDate(60)).withSchedule(simpleSchedule().withIntervalInSeconds(60).withRepeatCount(1)).build();
            //        // Tell quartz to schedule the job using our trigger
            scheduler.scheduleJob(jobDetail, trigger);
        }
    
  • 相关阅读:
    设计模式之 观察者模式
    设计模式之 模板方法模式
    设计模式之 状态模式
    设计模式之 策略模式
    设计模式之 桥接模式
    设计模式之 外观模式
    设计模式之 代理模式
    设计模式之 装饰者模式
    设计模式之 适配器模式
    设计模式之 组合模式
  • 原文地址:https://www.cnblogs.com/SimonHu1993/p/14421307.html
Copyright © 2020-2023  润新知