• 欢迎访问SimonHu的博客,推荐使用360浏览器和Chrome浏览器访问本网站

Springboot手动添加quartz-jobs

java SimonHu 3个月前 (02-20) 79次浏览 0个评论 扫描二维码

添加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);
    }

版权所有丨如未注明 , 均为原创丨
转载请注明原文链接:Springboot手动添加quartz-jobs
喜欢 (0)
[]
分享 (0)
关于作者:
Do you think that guy looks like a dog???
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址