Java定时任务定时器并没有那么难
Spring提供注解在指定时间去调用这个方法执行一次就可以
用到
@EnableScheduling
//一分钟执行一次
@Scheduled(cron = “0/60 * * * * ?”)
1、查询采集定时任务表collect_shop_task有没有要执行的定时任务
2、将要执行定时任务的集合按照商户分组组装成map
3、[important]获取output输出结果,并且更新成功记录 handlerBusinessOperator 处理业务操作工厂实现类,如类型标准对照、好店模型等
如果失败,进入捕获异常(定时任务这步是必须的)【定时任务有可能为批量,可能存在成功或失败,失败最好存到fail表】
@Slf4j@Component@EnableSchedulingpublic class CollectShopAutoTask { @Resource private CollectShopTaskService collectShopTaskService; //定时任务工厂 @Resource private CollectionShopHandlerService collectionShopHandlerService; @Scheduled(cron = "0/60 * * * * ?") public void execute() { log.info("采集店铺定时任务 collect shop task is start"); //1、查询采集定时任务表collect_shop_task有没有要执行的定时任务 List taskList = collectShopTaskService.listByStatus(CollectShopConstant.TASK_STATUS_INIT); if (CollectionUtil.isEmpty(taskList)) { log.info("no taskList, process is end"); return; } //2、将要执行定时任务的集合按照商户分组组装成map Map> merchantTaskMap = taskList.stream() .collect(Collectors.groupingBy(CollectShopTask::getMerchantId)); merchantTaskMap.forEach((key, value) -> { log.info("当前处理商户id:{}", key); value.forEach(collectShopTask -> { try { //3、获取output输出结果,并且更新成功记录 handlerBusinessOperator 处理业务操作工厂实现类,如类型标准对照、好店模型等 //获取对应的哪个service //定时任务工厂 处理工厂 CollectShopBusinessService collectShopBusinessService = collectionShopHandlerService.generateBusinessService(collectShopTask.getType()); //采集业务操作接口 处理业务操作工厂实现类,如类型标准对照、好店模型等,返回output String response = collectShopBusinessService.handlerBusinessOperator(collectShopTask); // 更新成功记录 collect_shop_task collectShopTaskService.updateSuccess(response, collectShopTask); } catch (Exception e) { //如果错误了,则捕获异常 log.error("处理商户:{}, 店铺:{}, 任务:{} 发生异常 e:{}", key, collectShopTask.getShopName(), CollectShopTaskEnum.getByType(collectShopTask.getType()).getText(), e); String failMess = "异常"; if (StringUtils.isNotEmpty(e.getMessage())) { failMess = e.getMessage().substring(0, (e.getMessage().length() > 1024 ? 1024 : e.getMessage().length())); } //collect_shop_task_fail_record collectShopTaskService.updateFail(failMess, collectShopTask); } }); }); }}