private void quartzOrderReturn(List<String> returnIds) { try { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put("returnIds", returnIds); //1. 创建一个JodDetail实例 将该实例与Hello job class绑定 (链式写法) JobDetail jobDetail = JobBuilder.newJob(QuartzOrderReturn.class)// 定义Job类为QuartzOrderReturn类,这是真正的执行逻辑所在 .withIdentity(StrUtils.uuid()) .setJobData(jobDataMap) .build(); // 2. 定义一个Trigger,定义该job在10秒后执行,并且执行一次 Date startTime = new Date(); startTime.setTime(startTime.getTime() + 10000L); SimpleTrigger trigger = TriggerBuilder.newTrigger() .withIdentity(StrUtils.uuid(), HeaderNameConstants.getQuartzTrigger()).startNow()// 定义名字和组 .startAt(startTime) .withSchedule(SimpleScheduleBuilder .simpleSchedule() .withIntervalInSeconds(2)//定义时间间隔是2秒 .withRepeatCount(0)//定义重复执行次数是无限次 ) .build(); // 4. 将trigger和jobdetail加入这个调度 scheduler.scheduleJob(jobDetail, trigger); // 5. 启动scheduler scheduler.start(); // 6. 任务执行后20秒后休眠 Thread.sleep(startTime.getTime() + 20000L); // 7. 如果定时任务开启则关闭 if (scheduler.isStarted()) { scheduler.shutdown(true); } } catch (SchedulerException | InterruptedException e) { e.printStackTrace(); } }
ublic static final Logger log = LoggerFactory.getLogger(Object.class); @Override public void execute(JobExecutionContext context) { try { log.info("执行定时任务开始"); JobDetail detail = context.getJobDetail(); List<String> returnIds = (List<String>) detail.getJobDataMap().get("returnIds"); OrderService orderService = (OrderService) SpringBeanFactoryUtils.getBeanByClass(OrderService.class); for (String returnId : returnIds) { orderService.refundPrice(returnId); } } catch (Exception e) { e.printStackTrace(); } }