【JAVA】quartz定时任务,自动过期,自动关闭等等,整合Springboot

  • Post author:
  • Post category:java


1. pom.xml

<!--定时任务-->
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.1</version>
</dependency>
<!-- 该依赖必加,里面有spring对schedule的支持 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>

2. 定时任务,用来触发定时任务

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhangenke
 * @Date: 2018-12-20 on 10:21
 * @description: 定时器,用来触发我们的任务:
 */
@Slf4j
@Component
public class MyScheduler {
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    private static Scheduler scheduler;
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Value("${submitOrderAuditExpiredValue}")
    private int submitOrderAuditExpiredValue;

    @Autowired
    private GetCronUtils getCronUtils;

    private final OrderDao orderDaoImpl;
    private final SupplierDao supplierDaoImpl;

    @Autowired
    public MyScheduler(OrderDao orderDaoImpl, SupplierDao supplierDaoImpl) {
        this.orderDaoImpl = orderDaoImpl;
        this.supplierDaoImpl = supplierDaoImpl;
    }

    /**
     * 项目启动时,需要自启动定时任务方法
     *
     * @throws SchedulerException
     */
    public void scheduleJobs() throws SchedulerException {
        log.info("开启定时任务:~~~~~~~~~~");
        scheduler = schedulerFactoryBean.getScheduler();
        this.orderAuditExpired();
        this.bidExpired();
    }

    /**
     * 订单下单审核自动过期任务,自启动后就会执行
     *
     * @param jobName          任务名
     * @param jobGroupName     任务组名
     * @param triggerName      触发器名
     * @param triggerGroupName 触发器组名
     * @throws SchedulerException
     */
    private void orderAuditExpired() throws SchedulerException {
        System.out.println("开始查询下单审核订单,设置时间为到点后,每分钟一次更新任务******************");
        System.out.println("现在时间:" + simpleDateFormat.format(new Date()));
        try {
            Map<JobDetail, Set<? extends Trigger>> map = Maps.newHashMap();
            log.info("正在查询所有下单等待审核的订单列表~~~~~~~~~");
            List<Order> orders = orderDaoImpl.listOrderAuditExpired();
            if (orders.size() > Num.ZERO.getNum()) {
                for (int i = 0; i < orders.size(); i++) {
                    log.info("下单时间:{}", simpleDateFormat.format(orders.get(i).getCreateAt()));
                    String cron = getCronUtils.getCron(orders.get(i).getCreateAt(), submitOrderAuditExpiredValue);
                    if (getCronUtils.compareTime(orders.get(i).getCreateAt(), submitOrderAuditExpiredValue)) {
                        cron = getCronUtils.getNowRandomCron();
                    }
                    log.info("时间表达式为:{}", cron);
                    // 1. 创建一个JodDetail实例 将该实例与Hello job class绑定 (链式写法)
                    // 定义Job类为ScheduledJob类,这是真正的执行逻辑所在
                    JobDetail jobDetail = JobBuilder.newJob(OrderAuditExpiredJob.class)
                            .withIdentity(orders.get(i).getOrderId(), orders.get(i).getOrderId())
                            .build();
                    CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                            .withIdentity(orders.get(i).getOrderId(), orders.get(i).getOrderId())
                            .withSchedule(
                                    CronScheduleBuilder.cronSchedule(cron)
                            ).build();
                    // 绑定 jobDetail 和 trigger,将它注册进 Scheduler 当中  ,返回值是最近一次任务执行的开始时间
                    //scheduler.scheduleJob(jobDetail, cronTrigger);
                    Set<Trigger> set = Sets.newHashSet();
                    set.add(cronTrigger);
                    map.put(jobDetail, set);
                    log.info("新增了:{}条", i + 1);
                }
                log.info("map size:{}", map.size());
                //新增定时任务组
                scheduler.scheduleJobs(map, false);
            } else {
                log.info("暂无订单审核任务需要审核:******");
            }
        } catch (Exception e) {
            log.error("订单审核定时任务错误:{}", e);
        }
    }

    private void bidExpired() throws SchedulerException {
        System.out.println("开始查询未已开标且未截止未关闭标书设置时间为到点后,每分钟一次******************");
        System.out.println("现在时间:" + simpleDateFormat.format(new Date()));
        try {
            Map<JobDetail, Set<? extends Trigger>> map = Maps.newHashMap();
            log.info("正在查询所有已开标且未截止招标标书列表~~~~~~~~~");
            List<Map> maps = supplierDaoImpl.listBidByExpired();
            //bidId,openBidTime
            if (maps.size() > Num.ZERO.getNum()) {
                for (int i = 0; i < maps.size(); i++) {
                    log.info("开标时间:{}", simpleDateFormat.format(maps.get(i).get("openBidTime")));
                    String cron = getCronUtils.getCron(simpleDateFormat.parse(maps.get(i).get("openBidTime").toString()), 0);
                    if (getCronUtils.compareTime(simpleDateFormat.parse(maps.get(i).get("openBidTime").toString()), 0)) {
                        cron = getCronUtils.getNowRandomCron();
                    }
                    log.info("时间表达式为:{}", cron);
                    JobDetail jobDetail = JobBuilder.newJob(BidExpiredJob.class)
                            .withIdentity(maps.get(i).get("bidId").toString(), maps.get(i).get("bidId").toString())
                            .build();
                    CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                            .withIdentity(maps.get(i).get("bidId").toString(), maps.get(i).get("bidId").toString())
                            .withSchedule(
                                    CronScheduleBuilder.cronSchedule(cron)
                            ).build();
                    Set<Trigger> set = Sets.newHashSet();
                    set.add(cronTrigger);
                    map.put(jobDetail, set);
                    log.info("新增了:{}条", i + 1);
                }
                log.info("map size:{}", map.size());
                //新增定时任务组
                scheduler.scheduleJobs(map, false);
            } else {
                log.info("暂无已开标且未截止及关闭的标书:******");
            }
        } catch (Exception e) {
            log.error("关闭标书定时任务错误:{}", e);
        }
    }

    /**
     * 新增定时任务
     *
     * @param cron             时间表达式
     * @param jobName          任务名
     * @param jobGroupName     任务组名
     * @param triggerName      触发器名
     * @param triggerGroupName 触发器组名
     * @param expiredClass     到时间需要执行的业务逻辑类
     * @throws SchedulerException
     */
    public void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Date date, int expiredValue, Class<? extends Job> expiredClass) throws SchedulerException {
        // 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = JobBuilder.newJob(expiredClass).withIdentity(jobName, jobGroupName).build();
        String cron = getCronUtils.getCron(date, expiredValue);
        // 基于表达式构建触发器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(triggerName, triggerGroupName)
                .withSchedule(scheduleBuilder).build();
        Date date1 = scheduler.scheduleJob(jobDetail, cronTrigger);
        log.info("新增定时任务成功,任务名:{},下次执行时间:{}", jobName, simpleDateFormat.format(date1));
    }


    /**
     * 修改某个任务的执行时间
     *
     * @param triggerName      触发器名
     * @param triggerGroupName 触发器组名
     * @param cron             时间表达式
     * @throws SchedulerException
     */
    public void modifyJob(String triggerName, String triggerGroupName, String cron) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        CronTrigger newTrigger = TriggerBuilder.newTrigger().withIdentity(triggerName, triggerGroupName)
                .withSchedule(scheduleBuilder).build();
        scheduler.rescheduleJob(triggerKey, newTrigger);
    }

    /**
     * 获取某个任务的状态
     *
     * @param triggerName
     * @param triggerGroupName
     * @return
     * @throws SchedulerException
     */
    public String getJobStatus(String triggerName, String triggerGroupName) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
        return scheduler.getTriggerState(triggerKey).name();
    }

    /**
     * 暂停某个任务
     *
     * @param jobName
     * @param jobGroupName
     * @throws SchedulerException
     */
    public void pauseJob(String jobName, String jobGroupName) throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey(jobName, jobGroupName));
    }

    /**
     * 恢复某个任务
     *
     * @param jobName
     * @param jobGroupName
     * @throws SchedulerException
     */
    public void resumeJob(String jobName, String jobGroupName) throws SchedulerException {
        scheduler.resumeJob(JobKey.jobKey(jobName, jobGroupName));
    }

    /**
     * 删除某个任务 (某个订单被审核,需要删除这个任务)
     *
     * @param jobName      任务名
     * @param jobGroupName 任务组名
     * @throws SchedulerException
     */
    public void deleteJob(String jobName, String jobGroupName) throws SchedulerException {
        scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));
    }


}

3. 监听器保证项目启动的时候会调用到

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhangenke
 * @Date: 2018-12-19 on 17:29
 * @description: 监听器保证项目启动的时候会调用到,我们的定时任务,代码如下:
 */
@Slf4j
@Configuration
public class SchedulerListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private MyScheduler myScheduler;

    @Autowired
    private JobFactory jobFactory;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            myScheduler.scheduleJobs();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 配置SchedulerFactoryBean
     * 将一个方法产生为Bean并交给Spring容器管理
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        // Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        // 设置自定义Job Factory,用于Spring管理Job bean
        factory.setJobFactory(jobFactory);
        return factory;
    }
}

4. 解决Springboot在Quartz中注入Bean的问题

package com.construn.procure.quartz;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhangenke @Date: 2018-12-26 on 15:56
 * @description: 解决SpringBoot不能再Quartz中注入Bean的问题
 */
@Component
public class JobFactory extends org.springframework.scheduling.quartz.SpringBeanJobFactory {
  /** AutowireCapableBeanFactory接口是BeanFactory的子类 可以连接和填充那些生命周期不被Spring管理的已存在的bean实例 */
  @Autowired
  private AutowireCapableBeanFactory beanFactory;

  /** 创建Job实例 */
  @Override
  protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
    // 实例化对象
    Object job = super.createJobInstance(bundle);
    // 进行注入(Spring管理该Bean)
    beanFactory.autowireBean(job);
    // 返回对象
    return job;
  }
}

5. 其中一个自动过期类

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhangenke @Date: 2018-12-20 on 10:21
 * @description: 订单下单审核自动过期任务
 * @description: 01-21 遇到Job初始化错误,原因是,Job类必须要有默认的无参构造方法!!!
 */
@Slf4j
@Component
public class BidExpiredJob implements Job {

  private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  @Autowired private SupplierDao supplierDaoImpl;
  @Autowired private UserClient userClient;

  public BidExpiredJob() {}

  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    log.info("订单过期任务开始执行:{}", simpleDateFormat.format(new Date()));
    try {
      log.info("标书正在关闭啊 ~~~~~~");
      userClient.updateBidStatusByExpired(jobExecutionContext.getJobDetail().getKey().getName());
      int count =
          supplierDaoImpl.updateBidStatusByExpired(
              jobExecutionContext.getJobDetail().getKey().getName());
      if (count != 1) {
        log.info("此标书状态已不是开标状态,已被关标,故不自动更新");
      } else {
        log.info("已自动过期:{}条", count);
      }
      log.info(
          "删除任务:{},必须是true,否则遇到了严重的错误",
          jobExecutionContext
              .getScheduler()
              .deleteJob(jobExecutionContext.getJobDetail().getKey()));
    } catch (Exception e) {
      log.error("订单过期任务出错,{}", e);
    }
  }
}

6. 时间表达式工具类

/**
 * Created with IntelliJ IDEA.
 *
 * @author: zhangenke
 * @Date: 2018-12-26 on 11:52
 * @description: 获取定时任务,时间表达式
 */
@Component
@Slf4j
public class GetCronUtils {
    private static final String SPACE = " ";

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取时间表达式,
     *
     * @param date         创建时间
     * @param expiredValue 过期值(单位秒)
     * @return
     */
    public String getCron(Date date, int expiredValue) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, expiredValue);
        return cron(calendar);

    }

    public String getNowRandomCron() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, new Random().nextInt(9) + 1);
        return cron(calendar);
    }

    /**
     * 如果他的时间加上五天,比现在的时间大,说明,已经过期,需要立刻执行过期逻辑
     *
     * @param oldDate
     * @param expiredValue 过期值
     * @return
     */
    public boolean compareTime(Date oldDate, int expiredValue) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(oldDate);
        calendar.add(Calendar.SECOND, expiredValue);
        log.info("任务时间 + {}天:{},现在时间:{}", expiredValue, simpleDateFormat.format(calendar.getTime()),
                simpleDateFormat.format(new Date()));
        if (calendar.getTime().getTime() < System.currentTimeMillis()) {
            log.info("任务时间 + {}天还是小与当前时间,所以已经严重超时,现在随机执行过期任务", expiredValue);
            return true;
        }
        return false;
    }


    private String cron(Calendar calendar) {
        int year = calendar.get(Calendar.YEAR);
        String month = (calendar.get(Calendar.MONTH) + 1) + "";
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        log.info("年,月,日,时,分,秒:{}-{}-{} {}:{}:{}", year, month, day, hour, minute, second);
        return second + SPACE + minute + "/1" + SPACE + hour +
                SPACE + day + SPACE + month + SPACE + "?" + SPACE + "*";
    }


}

7. 总结:

1. 首先要明确需求,再决定技术选型;

2. 遇到新技术,多打开几个博客园、CSDN博客等Demo,然后自己调试;

3. 遇到问题,再进行google解决。有很多问题前辈们都已经解决,你只需要找到而已;

4. 菜鸟分享,大佬勿喷;

5. @Autowired此注解,不能随便注入到构造函数类,否则会出现问题;

6. 所有出现的问题,我已经解决并且加了注释,都能看懂;



版权声明:本文为qq_17213067原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。