SpringBoot极简教程 · Spring Boot MyBatis+SpringMVC+SpringBootSpringBoot之路

08_SpringBoot集成Quartz

2018-06-12  本文已影响21人  明天你好向前奔跑

@Author Jacky Wang

转载请注明出处https://www.jianshu.com/p/b8a6c806fc3f

在工作中,我们常常需要使用到定时任务,Quartz是一个很好地任务框架,在这里记录下我使用SpringBoot集成Quartz实现多任务执行的方案。

一、pom引入jar包

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.3</version>
</dependency>

二、注册SpringBoot启动完成事件监听,用于启动job任务

@SpringBootConfiguration
public class SchedulerListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    public WSScheduler wsScheduler;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        wsScheduler.scheduleJobs(); 
    }
    
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); 
        return schedulerFactoryBean; 
    }
}

三、配置Job任务配置类

@Component
public class WSScheduler {

    private static final Logger logger = LoggerFactory.getLogger(WSScheduler.class);

    @Autowired
    private IVGApiProperty ivgApiProperty;
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    public void scheduleJobs() {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        try {
            syncAssetInfoJob(scheduler);
            addVipInfoJob(scheduler);
            addOrderInfoJob(scheduler);
        } catch (SchedulerException e) {
            logger.error("******Quartz scheduler job error,Cause>>>{}", e.getMessage());
        }
    }

    private void syncAssetInfoJob(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(SynAssetInfoTask.class).withIdentity("syncAssetInfoJob", "ivg").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(ivgApiProperty.getSyncAssetCron());
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("syncAssetInfoTrigger", "ivg")
                .withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    private void addVipInfoJob(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(AddVipInfoTask.class).withIdentity("addVipInfoJob", "ivg").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(ivgApiProperty.getAddVipInfoCron());
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("addVipInfoJobTrigger", "ivg")
                .withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    private void addOrderInfoJob(Scheduler scheduler) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(AddOrderInfoTask.class).withIdentity("addOrderInfoJob", "ivg").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(ivgApiProperty.getAddOrderInfoCron());
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("addOrderInfoTrigger", "ivg")
                .withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }
}

PS:里面相关的配置根据自身任务决定。其中ivgApiProperty中动态配置了各任务的执行时间间隔

四、实现各个Job任务

/**
 * @ClassName: addOrderInfoTask
 * @Description:TODO(推送订单任务类)
 * @author: wwj
 * @date: 2018年5月9日 下午4:17:04
 */
public class AddOrderInfoTask implements Job {

    private static final Logger logger = LoggerFactory.getLogger(AddOrderInfoTask.class);
    private static final String SERVICE_NAME = "middleWareServiceImpl";
    
    public IMiddleWareService getMiddleWareService() {
        return (IMiddleWareService)SpringUtils.getBean(SERVICE_NAME);
    }

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        getMiddleWareService().pushOrderInfo();
        logger.info("******推送订单定时任务执行完毕...");
    }
}

/**   
 * @ClassName:  addVipInfoTask   
 * @Description:TODO(推送会员任务类)   
 * @author: wwj
 * @date:   2018年5月9日 下午6:26:44   
 */  
public class AddVipInfoTask implements Job {

    private static final Logger logger = LoggerFactory.getLogger(AddVipInfoTask.class);
    
    private static final String SERVICE_NAME = "middleWareServiceImpl";

    public IMiddleWareService getMiddleWareService() {
        return (IMiddleWareService) SpringUtils.getBean(SERVICE_NAME);
    }

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        getMiddleWareService().pushVipInfo();
        logger.info("******推送会员定时任务执行完毕...");
    }
}

/**
 * @ClassName: SynAssetInfoTask
 * @Description:TODO(工作任务类)
 * @author: wwj
 * @date: 2018年5月9日 下午4:17:04
 */
public class SynAssetInfoTask implements Job {

    private static final Logger logger = LoggerFactory.getLogger(SynAssetInfoTask.class);
    private static final String SERVICE_NAME = "middleWareServiceImpl";

    public IMiddleWareService getMiddleWareService() {
        return (IMiddleWareService) SpringUtils.getBean(SERVICE_NAME);
    }

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        getMiddleWareService().syncAllWarehouseAsset();
        logger.info("******同步门店Asset定时任务执行完毕...");
    }
}

注意:因为实现Job任务的实现类并没有交给Spring来管理,因此不能注入Service等,因此我们自己创建了一个工具类来创建所需要的Service

五、创建SpringUtils工具类,创建所需对象

/**   
 * @ClassName:  SpringUtils   
 * @Description:TODO(系统bean帮助类)   
 * @author: wwj
 * @date:   2018年5月14日 上午11:36:39   
 */  
@Component
public class SpringUtils implements ApplicationContextAware {
    
    private static ApplicationContext context;

    @Override
    @SuppressWarnings("static-access")
    public void setApplicationContext(ApplicationContext contex) throws BeansException {
        this.context = contex;
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static String getMessage(String key) {
        return context.getMessage(key, null, Locale.getDefault());
    }
}

这样,Springboot项目启动就能正常执行任务了。这里Quartz的核心配置就在 WSScheduler 配置类中。

上一篇下一篇

猜你喜欢

热点阅读