在项目中,我们会用到定时任务做一系列的操作,比如多长时间优惠卷过期,定时发布动态,多少分钟之后支付订单过期之类的。
常见的是Java自带的定时器:
1.基于注解 (@Scheduled)
2.基于接口(SchedulingConfigurer)
3.基于注解设定多线程定时任务(@EnableAsync 开启多线程)

这里主要说的是springboot中整合quertz实现定时处理任务。

1.Quartz核心概念

任务 Job: Job 就是你想要实现的任务类,每一个 Job 必须实现org.quartz.job 接口,且只需实现接口定义的execute() 方法。

触发器 Trigger: Trigger 为你执行任务的触发器,比如你想每天定时3点统计昨天的订单数据发送给老板邮件,Trigger将会设置3点执行该任务。 Trigger主要包含两种 SimplerTrigger 和 CronTrigger 两种。

调度器 Scheduler: Scheduler 为任务的调度器,它会将任务 Job 及触发器 Trigger 整合起来,负责基于Trigger 设定的时间来执行 Job。

2.Quertz的使用

a.项目中引入jar 包
<dependencies>
	<!--定时器quartz的jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>
</dependencies>
b.创建一个demo
public class QuartzJob1 extends QuartzJobBean {

    @Autowired
    CouponMapper couponMapper;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { 
            System.out.println("这是一个定时任务");
    }

}
@Configuration
public class QuartzConfig {

    @Bean
    public JobDetail jobDetail1(){
        return JobBuilder.newJob(QuartzJob1.class).storeDurably().build();
    }

    @Bean
    public Trigger trigger1(){
        //cron 表达式 * * * * * ?
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/1 * * * ? ");
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail1()) //
                .withSchedule(scheduleBuilder)
                .build();
    }

}
3.在项目中整合运用
public interface IQuartzService {

    //1.添加定时任务
    void addTrigger(QuartzJobInfo jobInfo);

    //2.移除定时任务id
    void delTrigger(Long id);

    //2.移除定时任务id
    void deluser_depositTrigger(Long id);

    void delRefundUserDeposit_tigger(Long id);
}
@Service
public class QuartzServiceImpl implements IQuartzService {
    @Autowired
    private SchedulerFactoryBean factoryBean;

    @Override
    public void addTrigger(QuartzJobInfo jobInfo) {
        //jobInfo转换为json
        String info = JSONObject.toJSONString(jobInfo);
        //获取调度器
        Scheduler sche = factoryBean.getScheduler();
        //调用 工具类设置定时任务
        QuartzUtils.addJob(sche, jobInfo.getJobName(), OrderJob.class, info, jobInfo.getCronj());

    }

    @Override
    public void delTrigger(Long id) {
        //获取Job的名字
        String jobName = "product_job"+id;
        //获取调度器
        Scheduler sche = factoryBean.getScheduler();
        QuartzUtils.removeJob(sche,jobName);
    }

    @Override
    public void deluser_depositTrigger(Long id) {
        //获取Job的名字
        String jobName = "user_deposit"+id;
        //获取调度器
        Scheduler sche = factoryBean.getScheduler();
        QuartzUtils.removeJob(sche,jobName);
    }

    @Override
    public void delRefundUserDeposit_tigger(Long id) {
        //获取Job的名字
        String jobName = "refundUserDeposit_job"+id;
        //获取调度器
        Scheduler sche = factoryBean.getScheduler();
        QuartzUtils.removeJob(sche,jobName);
    }
}
public class OrderJob implements Job {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ParttimeJobMapper parttimeJobMapper;
    @Autowired
    IQuartzService iQuartzService;

    //遵循规范
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String params = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("params");
        QuartzJobInfo info = JSONObject.parseObject(params, QuartzJobInfo.class);
        byte type = info.getType();
        Date now = new Date();
        switch (type) {
            case JobTypeConsts.WAIT_PRODUCT_ORDER_PAY_CANCEL_JOB:
                Long productOrderId = Long.valueOf(info.getParams().get("orderId").toString());
                Order one = orderMapper.findOne(productOrderId);
                String s = AppPay.queryOrderResult(one.getOrder_number());
                if (now.compareTo(new Date(one.getCreation_time().getTime() + 300000)) == 1) {
                    if (!StringUtils.equals(s, "1")) {
                        orderMapper.updateStatus(one.getId(), -1, null);
                        iQuartzService.delTrigger(one.getId());
                    }

                } else {
                    if (StringUtils.equals(s, "1")) {
                        System.out.println(11);
                        parttimeJobMapper.updParttimejobStatus(one.getBinding_id(),1);
                        System.out.println(one);
                        orderMapper.updateStatus(one.getId(), 1, now);
                        iQuartzService.delTrigger(one.getId());
                    }
                }

                break;
            case JobTypeConsts.WAIT_USERDEPOSIT_ORDER_PAY_CANCEL_JOB:
                Long orderId = Long.valueOf(info.getParams().get("userPositId").toString());
                OrdersUserDeposit deposit = orderMapper.findOneUserDepsit(orderId);
                String userDepositPayStatus = AppPay.queryOrderResult(deposit.getOrder_number());
                if (now.compareTo(new Date(deposit.getCreation_time().getTime() + 300000)) == 1) {
                    if (!StringUtils.equals(userDepositPayStatus, "1")) {
                        orderMapper.updateOrdersUserDepositStatus(deposit.getId(), -1, null);
                        iQuartzService.deluser_depositTrigger(deposit.getId());
                    }
                } else {
                    if (StringUtils.equals(userDepositPayStatus, "1")) {
                        orderMapper.updateOrdersUserDepositStatus(deposit.getId(), 1, now);
                        iQuartzService.deluser_depositTrigger(deposit.getId());
                    }
                }

                break;
            case JobTypeConsts.WAIT_REFUNDUSERDEPOSIT_ORDER_PAY_CANCEL_JOB:
                Long refundUserDepositId = Long.valueOf(info.getParams().get("refundUserDepositId").toString());
                OrdersUserDeposit ordersUserDeposit = orderMapper.findOneUserDepsit(refundUserDepositId);
                String order = AppPay.selRefundOrder(ordersUserDeposit.getOrder_number());
                if (StringUtils.equals(order,"1")){
                    orderMapper.updateOrderUserDepositStatus(refundUserDepositId,1,new Date(),null);
                    iQuartzService.delRefundUserDeposit_tigger(ordersUserDeposit.getId());
                }else {
                    if (now.compareTo(new Date(ordersUserDeposit.getCreation_time().getTime() + 120000))==1){
                        orderMapper.delUserDeposit(refundUserDepositId);
                        iQuartzService.delRefundUserDeposit_tigger(ordersUserDeposit.getId());
                    }
                }

                break;
        }

    }

}
public class JobTypeConsts {
    /*用户订单表*/
    public static final byte WAIT_PRODUCT_ORDER_PAY_CANCEL_JOB = 1;
    /*用户押金支付*/
    public static final byte WAIT_USERDEPOSIT_ORDER_PAY_CANCEL_JOB = 2;
    /*用户押金退款*/
    public static final byte WAIT_REFUNDUSERDEPOSIT_ORDER_PAY_CANCEL_JOB = 3;
}
package cn.schoolgroup.quartz.utils;

import org.quartz.*;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * Quartz调度管理器
 * 
 */
public class QuartzUtils {
   private static String JOB_GROUP_NAME = "JOB_GROUP_SYSTEM";
   private static String TRIGGER_GROUP_NAME = "TRIGGER_GROUP_SYSTEM";

   /**
    * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
    * 
    * @param sched
    *            调度器
    * 
    * @param jobName
    *            任务名
    * @param cls
    *            任务
    * @param params
    *            任务参数
    * @param time
    *            时间设置,参考quartz说明文档
    * 
    * @Title: QuartzManager.java
    */
   public static void addJob(Scheduler sched, String jobName, @SuppressWarnings("rawtypes") Class cls, Object params,
         String time) {
      try {
         JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);// 任务名,任务组,任务执行类
         @SuppressWarnings("unchecked")

         JobDataMap jobDataMap = new JobDataMap();
         jobDataMap.put("params", params);
         JobDetail jobDetail = newJob(cls).withIdentity(jobKey).setJobData(jobDataMap).build();
         TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);// 触发器
         System.out.println(time);
         Trigger trigger = newTrigger().withIdentity(triggerKey).withSchedule(cronSchedule(time)).build();// 触发器时间设定
         sched.scheduleJob(jobDetail, trigger);
         if (!sched.isShutdown()) {
            sched.start();// 启动
         }
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   /**
    * @Description: 添加一个定时任务
    * 
    * @param sched
    *            调度器
    * 
    * @param jobName
    *            任务名
    * @param jobGroupName
    *            任务组名
    * @param triggerName
    *            触发器名
    * @param triggerGroupName
    *            触发器组名
    * @param jobClass
    *            任务
    * @param params
    *            任务参数
    * @param time
    *            时间设置,参考quartz说明文档
    * 
    * @Title: QuartzManager.java
    */
   public static void addJob(Scheduler sched, String jobName, String jobGroupName, String triggerName,
         String triggerGroupName, @SuppressWarnings("rawtypes") Class jobClass,  Object params, String time) {
      try {
         JobKey jobKey = new JobKey(jobName, jobGroupName);
         JobDataMap jobDataMap = new JobDataMap();
         jobDataMap.put("params", params);
         @SuppressWarnings("unchecked")
         JobDetail jobDetail = newJob(jobClass).withIdentity(jobKey).setJobData(jobDataMap).build();
         // 触发器
         TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
         Trigger trigger = newTrigger().withIdentity(triggerKey).withSchedule(cronSchedule(time)).build();
         sched.scheduleJob(jobDetail, trigger);
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   /**
    * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
    * 
    * @param sched
    *            调度器
    * @param jobName
    * @param time
    * 
    * @Title: QuartzManager.java
    */
   @SuppressWarnings("rawtypes")
   public static void modifyJobTime(Scheduler sched, String jobName, String time) {
      try {
         TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
         CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
         if (trigger == null) {
            return;
         }
         String oldTime = trigger.getCronExpression();
         if (!oldTime.equalsIgnoreCase(time)) {
            JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
            JobDetail jobDetail = sched.getJobDetail(jobKey);
            Class objJobClass = jobDetail.getJobClass();
            Object params = jobDetail.getJobDataMap().get("params");
            removeJob(sched, jobName);
            System.out.println("修改任务:" + jobName);
            addJob(sched, jobName, objJobClass, params,time);
         }
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   /**
    * @Description: 修改一个任务的触发时间
    * 
    * @param sched
    *            调度器 *
    * @param sched
    *            调度器
    * @param triggerName
    * @param triggerGroupName
    * @param time
    * 
    * @Title: QuartzManager.java
    */
   public static void modifyJobTime(Scheduler sched, String triggerName, String triggerGroupName, String time) {
      try {
         TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
         CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
         if (trigger == null) {
            return;
         }
         String oldTime = trigger.getCronExpression();
         if (!oldTime.equalsIgnoreCase(time)) {
            // 修改时间
            trigger.getTriggerBuilder().withSchedule(cronSchedule(time));
            // 重启触发器
            sched.resumeTrigger(triggerKey);
         }
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   /**
    * @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
    * 
    * @param sched
    *            调度器
    * @param jobName
    * 
    * @Title: QuartzManager.java
    */
   public static void removeJob(Scheduler sched, String jobName) {
      try {
         TriggerKey triggerKey = new TriggerKey(jobName, TRIGGER_GROUP_NAME);
         sched.pauseTrigger(triggerKey);// 停止触发器
         sched.unscheduleJob(triggerKey);// 移除触发器
         JobKey jobKey = new JobKey(jobName, JOB_GROUP_NAME);
         sched.deleteJob(jobKey);// 删除任务
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   /**
    * @Description: 移除一个任务
    * 
    * @param sched
    *            调度器
    * @param jobName
    * @param jobGroupName
    * @param triggerName
    * @param triggerGroupName
    * 
    * @Title: QuartzManager.java
    */
   public static void removeJob(Scheduler sched, String jobName, String jobGroupName, String triggerName,
         String triggerGroupName) {
      try {
         TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
         sched.pauseTrigger(triggerKey);// 停止触发器
         sched.unscheduleJob(triggerKey);// 移除触发器
         JobKey jobKey = new JobKey(jobName, jobGroupName);
         sched.deleteJob(jobKey);// 删除任务
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   /**
    * @Description:启动所有定时任务
    * 
    * @param sched  调度器
    * 
    * @Title: QuartzManager.java
    */
   public static void startJobs(Scheduler sched) {
      try {
         sched.start();
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   /**
    * @Description:关闭所有定时任务
    * 
    * @param sched
    *            调度器
    * 
    */
   public static void shutdownJobs(Scheduler sched) {
      try {
         if (!sched.isShutdown()) {
            sched.shutdown();
         }
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }
}