本文只是实时定时操作代码片段个的人记录,以防遗忘!
JAVA中有需要用到定时的地方,但有时候需求并不是隔一段时间去自动执行,而是在确切的时间去执行,这就需要创建特定准确时间的定时任务.
一:Service中部分代码
1.需要调用创建任务的地方
//创建任务定时执行更新活动商品缓存 Date startSalesDate = DateUtil.StringToDate(selectSingleActivity.getStartSaleTime(), "yyyy-MM-dd HH:mm:ss"); this.createJobActivityProductCache(id+"", startSalesDate);//创建任务定时执行更新活动商品缓存
2.创建定时任务的方法
public void createJobActivityProductCache(String activityId, Date date) throws SchedulerException { Scheduler sched = null; boolean flag = false; try { LOGGER.info("############## 定时更新活动商品缓存任务开始创建!"); String dateFormat="ss mm HH dd MM ? yyyy"; SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); String formatTimeStr = null; if (date != null) { formatTimeStr = sdf.format(date); } sched= SpringContextHolder.getBean("schedulerFactoryBean"); List<String> triggerGroupNames = sched.getTriggerGroupNames(); for (int i = 0; i < triggerGroupNames.size(); i++) { if(triggerGroupNames.get(i).contains("Group_Activity_RefreshCache_"+activityId)){ flag = true; } } //sched = StdSchedulerFactory.getDefaultScheduler(); //sched = schedulerFactoryBean.getScheduler(); TriggerKey triggerKey = TriggerKey.triggerKey("Job_Activity_RefreshCache_"+activityId, "Group_Activity_RefreshCache_"+activityId); //Trigger trigger1 = sched.getTrigger(triggerKey); JobDetail job = JobBuilder.newJob(ActivityRefreshCacheQuartzJob.class).withIdentity("Job_Activity_RefreshCache_"+activityId, "Group_Activity_RefreshCache_"+activityId).build(); //CronTrigger trigger1 = (CronTrigger) sched.getTrigger(triggerKey); if (!flag) { ScheduleJob scheduleJob = new ScheduleJob(); scheduleJob.setJobName("Job_Activity_RefreshCache_"+activityId); scheduleJob.setJobGroup("Group_Activity_RefreshCache_"+activityId); scheduleJob.setSpringId(activityId); scheduleJob.setDesc("定时更新活动商品缓存任务创建立"); job.getJobDataMap().put("scheduleRefreshCacheJob", scheduleJob); CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(CronScheduleBuilder.cronSchedule(formatTimeStr)).build(); Date ft = sched.scheduleJob(job, trigger); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); LOGGER.info(job.getKey() + " 已被安排执行于: " + sdf1.format(ft) + ",并且以如下重复规则重复执行: " + trigger.getCronExpression()); }else{ LOGGER.info("############## 定时任务已存在!"); // Trigger已存在,那么更新相应的定时设置 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(formatTimeStr); // 按新的cronExpression表达式重新构建trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); // 按新的trigger重新设置job执行 sched.rescheduleJob(triggerKey, trigger); } // 开始执行,start()方法被调用后,计时器就开始工作,计时调度中允许放入N个Job if(!sched.isShutdown()){ sched.start(); } //主线程等待一分钟 //Thread.sleep(60L * 1000L); } catch (SchedulerException e) { LOGGER.error("############## 定时更新活动商品缓存任务创建立 错误 ", e); } }
3.自动执行定时任务的JOB类 ActivityRefreshCacheQuartzJob
package com.pingan.zt.prms.web.scheduler; import org.quartz.DisallowConcurrentExecution; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.pingan.zt.prms.service.SalesActivityService; import com.pingan.zt.prms.utils.DateUtil; import com.pingan.zt.prms.utils.SpringContextHolder; /** * 定时扫描开卖时间到了要更新活动商品缓存 * * @author WANGWENXIANG185 * */ @DisallowConcurrentExecution public class ActivityRefreshCacheQuartzJob implements Job{ protected final Logger LOGGER = LoggerFactory.getLogger(ActivityRefreshCacheQuartzJob.class); @Override public void execute(JobExecutionContext context) throws JobExecutionException { //获取当前格式化时间 String currentDate = DateUtil.getCurrentDate(DateUtil.DATE_PATTEN_FORMATTER1); LOGGER.info(currentDate+"开始执行更新活动商品缓存开始"); SalesActivityService salesActivityService = (SalesActivityService) SpringContextHolder.getBean("salesActivityService"); ScheduleJob scheduleJob = (ScheduleJob)context.getMergedJobDataMap().get("scheduleRefreshCacheJob"); String id = scheduleJob.getSpringId(); LOGGER.info("时间=" + currentDate + " 执行了 1次"); // 1次 LOGGER.info("任务名称 = [" + scheduleJob.getJobName() + "]"); salesActivityService.updateActivityProductCache(Integer.parseInt(id)); LOGGER.info("定时更新活动商品缓存任务结束"); } }