/** * 所有正在运行的job * * @return * @throws SchedulerException */ public List<ScheduleJob> getRunningJob() throws SchedulerException { Scheduler scheduler = schedulerFactoryBean.getScheduler(); List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs(); List<ScheduleJob> jobList = new ArrayList<ScheduleJob>(executingJobs.size()); for (JobExecutionContext executingJob : executingJobs) { ScheduleJob job = new ScheduleJob(); JobDetail jobDetail = executingJob.getJobDetail(); JobKey jobKey = jobDetail.getKey(); Trigger trigger = executingJob.getTrigger(); job.setName(jobKey.getName()); job.setGroup(jobKey.getGroup()); job.setDescription("触发器:" + trigger.getKey()); Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); job.setStatus(triggerState.name()); if (trigger instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger) trigger; String cronExpression = cronTrigger.getCronExpression(); job.setCron(cronExpression); } jobList.add(job); } return jobList; }
/** * 获取所有计划中的任务列表 * * @return * @throws SchedulerException */ public List<ScheduleJob> getAllJob() throws SchedulerException { Scheduler scheduler = schedulerFactoryBean.getScheduler(); GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup(); Set<JobKey> jobKeys = scheduler.getJobKeys(matcher); List<ScheduleJob> jobList = new ArrayList<ScheduleJob>(); for (JobKey jobKey : jobKeys) { List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey); for (Trigger trigger : triggers) { ScheduleJob job = new ScheduleJob(); job.setName(jobKey.getName()); job.setGroup(jobKey.getGroup()); job.setDescription("触发器:" + trigger.getKey()); Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); job.setStatus(triggerState.name()); if (trigger instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger) trigger; String cronExpression = cronTrigger.getCronExpression(); job.setCron(cronExpression); } jobList.add(job); } } return jobList; }
/** * The user may configure this binding to update the internal clock of * FHT80b devices via rf command. The method takes care of scheduling this * job. */ private JobKey scheduleJob(Class<? extends Job> jobClass, String cronExpression) { JobKey jobKey = null; try { Scheduler sched = StdSchedulerFactory.getDefaultScheduler(); JobDetail detail = JobBuilder.newJob(jobClass).withIdentity("FHT "+jobClass.getSimpleName(), "cul").build(); detail.getJobDataMap().put(FHTBinding.class.getName(), this); CronTrigger trigger = TriggerBuilder.newTrigger().forJob(detail) .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build(); jobKey = detail.getKey(); sched.scheduleJob(detail, trigger); } catch (SchedulerException e) { logger.error("Can't schedule time update job", e); } return jobKey; }
/** * Build the cron trigger * * @return The trigger * @throws Exception */ public Trigger getTrigger() throws Exception { Trigger trigger = new CronTrigger(getBeanName(), Scheduler.DEFAULT_GROUP, getCronExpression()); if (this.startDelay > 0) { trigger.setStartTime(new Date(System.currentTimeMillis() + this.startDelay)); } JobDetail jd = super.getJobDetail(); if (jd != null) { String jobName = super.getJobDetail().getKey().getName(); if (jobName != null && !jobName.isEmpty()) { trigger.setJobName(jobName); } String jobGroup = super.getJobDetail().getKey().getGroup(); if (jobGroup != null && !jobGroup.isEmpty()) { trigger.setJobGroup(jobGroup); } } return trigger; }
private void wrapScheduleJob(ScheduleJob scheduleJob,Scheduler scheduler,JobKey jobKey,Trigger trigger){ try { scheduleJob.setJobName(jobKey.getName()); scheduleJob.setJobGroup(jobKey.getGroup()); JobDetail jobDetail = scheduler.getJobDetail(jobKey); ScheduleJob job = (ScheduleJob)jobDetail.getJobDataMap().get("scheduleJob"); scheduleJob.setDesc(job.getDesc()); scheduleJob.setJobId(job.getJobId()); Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); scheduleJob.setJobStatus(triggerState.name()); if(trigger instanceof CronTrigger){ CronTrigger cronTrigger = (CronTrigger)trigger; String cronExpression = cronTrigger.getCronExpression(); scheduleJob.setCronExpression(cronExpression); } } catch (SchedulerException e) { e.printStackTrace(); } }
public void start(){ for(int index = 0; index < jobList.size(); index++){ JobInfo jobInfo = jobList.get(index); String logTitle = "[" + code + "]" + jobInfo.getName() + " "; try{ SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); JobDetail job = newJob(DataTask.class).withIdentity("job-" + jobInfo.getName(), code).build(); job.getJobDataMap().put("srcDb", srcDb); job.getJobDataMap().put("destDb", destDb); job.getJobDataMap().put("jobInfo", jobInfo); job.getJobDataMap().put("logTitle", logTitle); logger.info(jobInfo.getCron()); CronTrigger trigger = newTrigger() .withIdentity("trigger-" + jobInfo.getName(), code) .withSchedule(cronSchedule(jobInfo.getCron())).build(); sched.scheduleJob(job, trigger); sched.start(); }catch(Exception e){ logger.info(logTitle + e.getMessage()); logger.info(logTitle + " run failed"); continue; } } }
public void JobRegist() throws Exception { Class<?> c = null; // 등록할 스케줄 정보 설정 setSchList(); for (int j = 0; j < schDTO.length; j++) { try { c = Class.forName(schDTO[j].getTask_class()); jobDetail = new JobDetail(schDTO[j].getTask_id(), schDTO[j].getTask_group_id(), c); trigger = new CronTrigger(schDTO[j].getTask_id(), schDTO[j].getTask_group_id()); trigger.setCronExpression(schDTO[j].getTask_expression()); scheduler.scheduleJob(jobDetail, trigger); } catch (Exception e) { throw e; } } }
public int insertExtendedTriggerProperties(Connection conn, OperableTrigger trigger, String state, JobDetail jobDetail) throws SQLException, IOException { CronTrigger cronTrigger = (CronTrigger)trigger; PreparedStatement ps = null; try { ps = conn.prepareStatement(Util.rtp(INSERT_CRON_TRIGGER, tablePrefix, schedNameLiteral)); ps.setString(1, trigger.getKey().getName()); ps.setString(2, trigger.getKey().getGroup()); ps.setString(3, cronTrigger.getCronExpression()); ps.setString(4, cronTrigger.getTimeZone().getID()); return ps.executeUpdate(); } finally { Util.closeStatement(ps); } }
public int updateExtendedTriggerProperties(Connection conn, OperableTrigger trigger, String state, JobDetail jobDetail) throws SQLException, IOException { CronTrigger cronTrigger = (CronTrigger)trigger; PreparedStatement ps = null; try { ps = conn.prepareStatement(Util.rtp(UPDATE_CRON_TRIGGER, tablePrefix, schedNameLiteral)); ps.setString(1, cronTrigger.getCronExpression()); ps.setString(2, cronTrigger.getTimeZone().getID()); ps.setString(3, trigger.getKey().getName()); ps.setString(4, trigger.getKey().getGroup()); return ps.executeUpdate(); } finally { Util.closeStatement(ps); } }
/** * Get a {@link ScheduleBuilder} that is configured to produce a * schedule identical to this trigger's schedule. * * @see #getTriggerBuilder() */ @Override public ScheduleBuilder<CronTrigger> getScheduleBuilder() { CronScheduleBuilder cb = CronScheduleBuilder.cronSchedule(getCronExpression()) .inTimeZone(getTimeZone()); switch(getMisfireInstruction()) { case MISFIRE_INSTRUCTION_DO_NOTHING : cb.withMisfireHandlingInstructionDoNothing(); break; case MISFIRE_INSTRUCTION_FIRE_ONCE_NOW : cb.withMisfireHandlingInstructionFireAndProceed(); break; } return cb; }
public static CompositeData toCompositeData(CronTrigger trigger) { try { return new CompositeDataSupport(COMPOSITE_TYPE, ITEM_NAMES, new Object[] { trigger.getCronExpression(), trigger.getTimeZone(), trigger.getKey().getName(), trigger.getKey().getGroup(), trigger.getJobKey().getName(), trigger.getJobKey().getGroup(), trigger.getDescription(), JobDataMapSupport.toTabularData(trigger .getJobDataMap()), trigger.getCalendarName(), ((OperableTrigger)trigger).getFireInstanceId(), trigger.getMisfireInstruction(), trigger.getPriority(), trigger.getStartTime(), trigger.getEndTime(), trigger.getNextFireTime(), trigger.getPreviousFireTime(), trigger.getFinalFireTime() }); } catch (OpenDataException e) { throw new RuntimeException(e); } }
/** * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名) * @param jobName * @param time * */ @SuppressWarnings("unchecked") public static void modifyJobTime(String jobName, String time) { TriggerKey triggerKey = TriggerKey.triggerKey( jobName, TRIGGER_GROUP_NAME); try { Scheduler sched = gSchedulerFactory.getScheduler(); CronTrigger trigger =(CronTrigger) sched.getTrigger(triggerKey); if (trigger == null) { return; } String oldTime = trigger.getCronExpression(); if (!oldTime.equalsIgnoreCase(time)) { CronScheduleBuilder scheduleBuilder =CronScheduleBuilder.cronSchedule(time); //按新的cronExpression表达式重新构建trigger trigger = trigger.getTriggerBuilder().withIdentity(triggerKey) .withSchedule(scheduleBuilder).build(); //按新的trigger重新设置job执行 sched.rescheduleJob(triggerKey, trigger); } } catch (Exception e) { throw new RuntimeException(e); } }
/** * @Description: 修改一个任务的触发时间 * @param triggerName * @param triggerGroupName * @param time * * */ public static void modifyJobTime(String triggerName, String triggerGroupName, String time) { TriggerKey triggerKey = TriggerKey.triggerKey( triggerName, triggerGroupName); try { Scheduler sched = gSchedulerFactory.getScheduler(); CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey); if (trigger == null) { return; } String oldTime = trigger.getCronExpression(); if (!oldTime.equalsIgnoreCase(time)) { // trigger已存在,则更新相应的定时设置 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder .cronSchedule(time); // 按新的cronExpression表达式重新构建trigger trigger = trigger.getTriggerBuilder().withIdentity(triggerKey) .withSchedule(scheduleBuilder).build(); // 按新的trigger重新设置job执行 sched.resumeTrigger(triggerKey); } } catch (Exception e) { throw new RuntimeException(e); } }
/** * <p> * Insert the cron trigger data. * </p> * * @param conn * the DB Connection * @param trigger * the trigger to insert * @return the number of rows inserted */ public int insertCronTrigger(Connection conn, CronTrigger trigger) throws SQLException { PreparedStatement ps = null; try { ps = conn.prepareStatement(rtp(INSERT_CRON_TRIGGER)); ps.setString(1, trigger.getName()); ps.setString(2, trigger.getGroup()); ps.setString(3, trigger.getCronExpression()); ps.setString(4, trigger.getTimeZone().getID()); return ps.executeUpdate(); } finally { closeStatement(ps); } }
/** * <p> * Update the cron trigger data. * </p> * * @param conn * the DB Connection * @param trigger * the trigger to insert * @return the number of rows updated */ public int updateCronTrigger(Connection conn, CronTrigger trigger) throws SQLException { PreparedStatement ps = null; try { ps = conn.prepareStatement(rtp(UPDATE_CRON_TRIGGER)); ps.setString(1, trigger.getCronExpression()); ps.setString(2, trigger.getName()); ps.setString(3, trigger.getGroup()); return ps.executeUpdate(); } finally { closeStatement(ps); } }
@Transactional @Override public boolean addJobTrigger(ScheduleJobEntity job) { try { Scheduler scheduler = schedulerFactoryBean.getScheduler(); // 表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder .cronSchedule(job.getCronExpression()); // 按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = newTrigger() .forJob(job.getJobKey()) //绑定job .withIdentity(job.getTriggerKey()) .startAt(job.getStartDate()) // job开始日期 .endAt(job.getEndDate())// job结束日期 .withSchedule(scheduleBuilder).build(); // 将trigger添加到quartz的scheduler容器 scheduler.scheduleJob(trigger); return Boolean.TRUE; } catch (SchedulerException e) { throw new ServiceException(e); } }
/** * 封装ScheduleJob对象 * * @param scheduleJob * @param scheduler * @param jobKey * @param trigger */ private void wrapScheduleJob(ScheduleJobEntity scheduleJob, Scheduler scheduler, JobKey jobKey, Trigger trigger) { try { scheduleJob.setJobName(jobKey.getName()); scheduleJob.setJobGroup(jobKey.getGroup()); JobDetail jobDetail = scheduler.getJobDetail(jobKey); scheduleJob.setJobClass(jobDetail.getJobClass()); scheduleJob.setJobDesc(jobDetail.getDescription()); Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); scheduleJob.setTriggerStatus(triggerState.name()); if (trigger instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger) trigger; TriggerKey triggerKey = cronTrigger.getKey(); scheduleJob.setTriggerName(triggerKey.getName()); scheduleJob.setTriggerGroup(triggerKey.getGroup()); scheduleJob.setNextFireTime(cronTrigger.getNextFireTime()); scheduleJob.setCronExpression(cronTrigger.getCronExpression()); scheduleJob.setStartDate(cronTrigger.getStartTime()); scheduleJob.setEndDate(cronTrigger.getEndTime()); } } catch (SchedulerException e) { logger.error("获取触发器状态失败", e); throw new ServiceException(e); } }
public serverTasks() throws SchedulerException, ParseException{ /* * 循环式的 */ SchedulerFactory factory = new StdSchedulerFactory(); Scheduler scheduler = factory.getScheduler(); //设置启动时间 DateBuilder.evenMinuteDate(new Date()); JobDetail job = JobBuilder.newJob(job.class).withIdentity("job1", "group1").build(); //job.getJobDataMap().put("a", true);//实现传参 // @NOTICE // 与SimpleTrigger对比:类不同了,现在的是Trigger的子类CronTrigger;withSchedule中的参数变为CronScheduleBuilder了 // CronScheduleBuilder可以通过类似"0/13 * * * * ?"这种表达式来创建定时任务 // 当前这个表达式的定义是30分钟执行一次 CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1") .withSchedule(CronScheduleBuilder.cronSchedule("1 0/30 * * * ?")).build(); scheduler.scheduleJob(job, trigger); scheduler.start(); //scheduler.shutdown(true); }
private void addJob(ScheduleJob scheduleJob) throws Exception{ checkNotNull(scheduleJob); Preconditions.checkNotNull(StringUtils.isEmpty(scheduleJob.getCronExpression()), "CronExpression is null"); TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup()); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); if(trigger != null){ throw new Exception("job already exists!"); } // simulate job info db persist operation scheduleJob.setJobId(String.valueOf(QuartzJobFactory.jobList.size()+1)); QuartzJobFactory.jobList.add(scheduleJob); JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class).withIdentity(scheduleJob.getJobName(),scheduleJob.getJobGroup()).build(); jobDetail.getJobDataMap().put("scheduleJob", scheduleJob); CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()); trigger = TriggerBuilder.newTrigger().withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).withSchedule(cronScheduleBuilder).build(); scheduler.scheduleJob(jobDetail, trigger); }
/** * 创建定时任务 */ public static void createScheduleJob(Scheduler scheduler, ScheduleJobEntity scheduleJob) { try { //构建job信息 JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getJobId())).build(); //表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()) .withMisfireHandlingInstructionDoNothing(); //按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getJobId())).withSchedule(scheduleBuilder).build(); //放入参数,运行时的方法可以获取 jobDetail.getJobDataMap().put(ScheduleJobEntity.JOB_PARAM_KEY, new Gson().toJson(scheduleJob)); scheduler.scheduleJob(jobDetail, trigger); //暂停任务 if(scheduleJob.getStatus() == ScheduleStatus.PAUSE.getValue()){ pauseJob(scheduler, scheduleJob.getJobId()); } } catch (SchedulerException e) { throw new RRException("创建定时任务失败", e); } }
/** * 创建定时任务 */ public static void createScheduleJob(Scheduler scheduler, ScheduleJobEntity scheduleJob) { try { //构建job信息 JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getJobId())).build(); //表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()); //按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getJobId())).withSchedule(scheduleBuilder).build(); //放入参数,运行时的方法可以获取 jobDetail.getJobDataMap().put(ScheduleJobEntity.JOB_PARAM_KEY, scheduleJob); scheduler.scheduleJob(jobDetail, trigger); //暂停任务 if(scheduleJob.getStatus() == ScheduleStatus.PAUSE.getValue()){ pauseJob(scheduler, scheduleJob.getJobId()); } } catch (SchedulerException e) { throw new RRException("创建定时任务失败", e); } }
@Override public Optional<CrontabEntry> getSchedule(IJobKey jobKey) throws IllegalStateException { requireNonNull(jobKey); try { return Optional.of(Iterables.getOnlyElement( FluentIterable.from(scheduler.getTriggersOfJob(jobKey(jobKey))) .filter(CronTrigger.class) .transform(Quartz::crontabEntry))); } catch (SchedulerException e) { LOG.error( "Error reading job " + JobKeys.canonicalString(jobKey) + " cronExpression Quartz: " + e, e); return Optional.absent(); } }
@Override public Map<IJobKey, CrontabEntry> getScheduledJobs() { // NOTE: no synchronization is needed here since this is just a dump of internal quartz state // for debugging. ImmutableMap.Builder<IJobKey, CrontabEntry> scheduledJobs = ImmutableMap.builder(); try { for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.anyGroup())) { // The quartz API allows jobs to have multiple triggers. We don't use that feature but // we're defensive here since this function is used for debugging. Optional<CronTrigger> trigger = FluentIterable.from(scheduler.getTriggersOfJob(jobKey)) .filter(CronTrigger.class) .first(); if (trigger.isPresent()) { scheduledJobs.put( Quartz.auroraJobKey(jobKey), Quartz.crontabEntry(trigger.get())); } } } catch (SchedulerException e) { throw Throwables.propagate(e); } return scheduledJobs.build(); }
public void JobRegist() throws Exception { Class c = null; // 등록할 스케줄 정보 설정 setSchList(); for (int j = 0; j < schDTO.length; j++) { try { c = Class.forName(schDTO[j].getTask_class()); jobDetail = new JobDetail(schDTO[j].getTask_id(), schDTO[j].getTask_group_id(), c); trigger = new CronTrigger(schDTO[j].getTask_id(), schDTO[j].getTask_group_id()); trigger.setCronExpression(schDTO[j].getTask_expression()); scheduler.scheduleJob(jobDetail, trigger); } catch (Exception e) { throw e; } } }
public SchedulerFactoryBean build() throws Exception { SchedulerFactoryBean bean = new SchedulerFactoryBean(); PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource(config)); propertiesFactoryBean.afterPropertiesSet(); Properties props = propertiesFactoryBean.getObject(); List<Trigger> triggers = Lists.newArrayList(); List<JobModel> jobList = getJobs(props); for (JobModel job : jobList) { if (!job.isEnable()) { continue; } JobDetailFactoryBean detail = createJobDetail(job.getName(), Class.forName(job.getJob())); CronTriggerFactoryBean trigger = createCronTrigger(job.getName(), detail.getObject(), job.getCorn()); CronTrigger t = trigger.getObject(); triggers.add(t); } bean.setTriggers(triggers.toArray(new Trigger[0])); //bean.afterPropertiesSet(); return bean; }
@Override public void schedule(String jobName, CronExpression cronExpression) { try { if(jobDetail != null){ jobDetail.setName(jobName); jobDetail.setGroup(JOB_GROUP_NAME); CronTrigger cronTrigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME); cronTrigger.setCronExpression(cronExpression); scheduler.scheduleJob(jobDetail,cronTrigger); if(!scheduler.isShutdown()) scheduler.start(); }else{ log.error("定时任务 "+jobName+" jobDetail对象为空"); //System.out.println("定时任务 "+jobName+" jobDetail对象为空"); } // scheduler.rescheduleJob(name, Scheduler.DEFAULT_GROUP, cronTrigger); } catch (SchedulerException e) { log.error(e); throw new RuntimeException(e); } }
public boolean modifyJob(String jobName, String cronExpression) throws SchedulerException, ParseException { boolean flag = false; CronTrigger trigger = (CronTrigger) scheduler.getTrigger(jobName, TRIGGER_GROUP_NAME); if (trigger != null) { if (StringUtils.equals(trigger.getCronExpression(), cronExpression)) { log.info(jobName + " : 定时任务表达式一致、不需要修改"); flag = true; } else { trigger.setCronExpression(cronExpression); scheduler.rescheduleJob(trigger.getName(), trigger.getGroup(), trigger); log.info(jobName + " : 定时任务修改成功"); flag = true; } } return flag; }
public static String showStatus(){ StringBuilder sb = new StringBuilder(); try { if(null != scheduler && scheduler.isStarted()){ sb.append("<h1>------------------QuartzUtils status:RUNNING---------------------</h1>"); String[] names = scheduler.getJobNames(Scheduler.DEFAULT_GROUP); if(names!=null){ for(int i = 0; i<names.length;i++){ JobDetail jd =scheduler.getJobDetail(names[i], Scheduler.DEFAULT_GROUP); sb.append("<p>").append(jd.toString()).append("</p>"); Trigger t = scheduler.getTrigger(names[i]+"Trigger", Scheduler.DEFAULT_GROUP); if(t instanceof CronTrigger){ sb.append("<p>").append("triggered at: ").append(((CronTrigger)t).getCronExpression()).append("</p>"); } } } }else{ sb.append("<h1>------------------QuartzUtils status:CLOSED---------------------</h1>"); } } catch (SchedulerException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sb.toString(); }
/** * 获取运行中的任务 */ public List<ScheduleJob> getRunningJobs() throws SchedulerException { Scheduler scheduler = schedulerFactoryBean.getScheduler(); List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs(); List<ScheduleJob> jobList = new ArrayList<ScheduleJob>(executingJobs.size()); for (JobExecutionContext executingJob : executingJobs) { ScheduleJob job = new ScheduleJob(); JobDetail jobDetail = executingJob.getJobDetail(); JobKey jobKey = jobDetail.getKey(); Trigger trigger = executingJob.getTrigger(); job.setJobId(jobKey.getGroup() + "_" + jobKey.getName()); job.setJobName(jobKey.getName()); job.setJobGroup(jobKey.getGroup()); job.setDesc(trigger.getDescription()); Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey()); job.setJobStatus(triggerState.name()); if (trigger instanceof CronTrigger) { CronTrigger cronTrigger = (CronTrigger) trigger; String cronExpression = cronTrigger.getCronExpression(); job.setCronExpression(cronExpression); } jobList.add(job); } return jobList; }
/** * 新增单个任务 Cron */ public void scheduleCronNewJob(ScheduleJob scheduleJob) throws SchedulerException, ClassNotFoundException { Scheduler scheduler = schedulerFactoryBean.getScheduler(); TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup()); // 获取trigger,即在spring配置文件中定义的bean id="myTrigger" CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 不存在,创建一个 JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(scheduleJob.getJobClass())) .withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).withDescription( scheduleJob.getDesc()).build(); // 表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()); // 按新的cronExpression表达式构建一个新的trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); scheduler.scheduleJob(jobDetail, trigger); }
@Test public void testConfigureCronExpression() throws Exception { QuartzEndpoint endpoint = resolveMandatoryEndpoint("quartz2://myGroup/myTimerName?cron=0+0/5+12-18+?+*+MON-FRI"); Scheduler scheduler = endpoint.getComponent().getScheduler(); TriggerKey triggerKey = endpoint.getTriggerKey(); Trigger trigger = scheduler.getTrigger(triggerKey); JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey(triggerKey.getName(), triggerKey.getGroup())); assertEquals("getName()", "myTimerName", triggerKey.getName()); assertEquals("getGroup()", "myGroup", triggerKey.getGroup()); assertEquals("getJobName", "myTimerName", jobDetail.getKey().getName()); assertEquals("getJobGroup", "myGroup", jobDetail.getKey().getGroup()); assertIsInstanceOf(CronTrigger.class, trigger); CronTrigger cronTrigger = (CronTrigger)trigger; assertEquals("cron expression", "0 0/5 12-18 ? * MON-FRI", cronTrigger.getCronExpression()); }
@Test public void testConfigureAnotherCronExpression() throws Exception { QuartzEndpoint endpoint = resolveMandatoryEndpoint("quartz2://myGroup/myTimerName?cron=0+0+*+*+*+?"); Scheduler scheduler = endpoint.getComponent().getScheduler(); TriggerKey triggerKey = endpoint.getTriggerKey(); Trigger trigger = scheduler.getTrigger(triggerKey); JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey(triggerKey.getName(), triggerKey.getGroup())); assertEquals("getName()", "myTimerName", triggerKey.getName()); assertEquals("getGroup()", "myGroup", triggerKey.getGroup()); assertEquals("getJobName", "myTimerName", jobDetail.getKey().getName()); assertEquals("getJobGroup", "myGroup", jobDetail.getKey().getGroup()); assertIsInstanceOf(CronTrigger.class, trigger); CronTrigger cronTrigger = (CronTrigger)trigger; assertEquals("cron expression", "0 0 * * * ?", cronTrigger.getCronExpression()); }
@Test public void testConfigureJobName() throws Exception { QuartzEndpoint endpoint = resolveMandatoryEndpoint("quartz2://myGroup/myTimerName?job.name=hadrian&cron=0+0+*+*+*+?"); Scheduler scheduler = endpoint.getComponent().getScheduler(); TriggerKey triggerKey = endpoint.getTriggerKey(); Trigger trigger = scheduler.getTrigger(triggerKey); JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey("hadrian", triggerKey.getGroup())); assertEquals("getName()", "myTimerName", triggerKey.getName()); assertEquals("getGroup()", "myGroup", triggerKey.getGroup()); assertEquals("getJobName", "hadrian", jobDetail.getKey().getName()); assertEquals("getJobGroup", "myGroup", jobDetail.getKey().getGroup()); assertIsInstanceOf(CronTrigger.class, trigger); }
@Test public void testConfigureNoDoubleSlashQuestionCron() throws Exception { QuartzEndpoint endpoint = resolveMandatoryEndpoint("quartz2:myGroup/myTimerName?cron=0+0+*+*+*+?"); Scheduler scheduler = endpoint.getComponent().getScheduler(); TriggerKey triggerKey = endpoint.getTriggerKey(); Trigger trigger = scheduler.getTrigger(triggerKey); JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey(triggerKey.getName(), triggerKey.getGroup())); assertEquals("getName()", "myTimerName", triggerKey.getName()); assertEquals("getGroup()", "myGroup", triggerKey.getGroup()); assertEquals("getJobName", "myTimerName", jobDetail.getKey().getName()); assertEquals("getJobGroup", "myGroup", jobDetail.getKey().getGroup()); assertIsInstanceOf(CronTrigger.class, trigger); CronTrigger cronTrigger = (CronTrigger)trigger; assertEquals("cron expression", "0 0 * * * ?", cronTrigger.getCronExpression()); }
@Test public void testQuartzCronRoute() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(3); assertMockEndpointsSatisfied(); Trigger trigger = mock.getReceivedExchanges().get(0).getIn().getHeader("trigger", Trigger.class); Assert.assertThat(trigger instanceof CronTrigger, CoreMatchers.is(true)); JobDetail detail = mock.getReceivedExchanges().get(0).getIn().getHeader("jobDetail", JobDetail.class); Assert.assertThat(detail.getJobClass().equals(CamelJob.class), CoreMatchers.is(true)); Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_TYPE).equals("cron"), CoreMatchers.is(true)); Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_CRON_EXPRESSION).equals("0/2 * * * * ?"), CoreMatchers.is(true)); }
/** * 创建定时任务 * * @param scheduler * the scheduler * @param jobName * the job name * @param jobGroup * the job group * @param cronExpression * the cron expression * @param isSync * the is sync * @param param * the param */ public static boolean createScheduleJob(Scheduler scheduler, String jobName, String jobGroup, String cronExpression, boolean isSync, Object param) { boolean result = false; // 同步或异步 Class<? extends Job> jobClass = JobFactory.getInstance(isSync); // 构建job信息 JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroup).build(); // 放入参数,运行时的方法可以获取,资料:http://www.cnblogs.com/wyqtomorrow/archive/2007/04/28/730963.html jobDetail.getJobDataMap().put(ScheduleJobBo.JOB_PARAM_KEY, param); // 表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression); // 按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup).withSchedule(scheduleBuilder) .build(); try { Date nextExexuteDate = scheduler.scheduleJob(jobDetail, trigger);// 任务创建成功,会返回下一次执行的时间 if (nextExexuteDate != null) { result = true; } } catch (SchedulerException e) { LOG.error("创建定时任务失败", e); return false; } return result; }