示例#1
0
  @Test
  public void testScheduleMultipleTriggersForAJob() throws SchedulerException {
    JobDetail job = newJob(TestJob.class).withIdentity("job1", "group1").build();
    Trigger trigger1 =
        newTrigger()
            .withIdentity("trigger1", "group1")
            .startNow()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
            .build();
    Trigger trigger2 =
        newTrigger()
            .withIdentity("trigger2", "group1")
            .startNow()
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
            .build();
    Set<Trigger> triggersForJob = new HashSet<Trigger>();
    triggersForJob.add(trigger1);
    triggersForJob.add(trigger2);

    Scheduler sched = createScheduler("testScheduleMultipleTriggersForAJob", 5);
    sched.scheduleJob(job, triggersForJob, true);

    List<? extends Trigger> triggersOfJob = sched.getTriggersOfJob(job.getKey());
    assertEquals(2, triggersOfJob.size());
    assertTrue(triggersOfJob.contains(trigger1));
    assertTrue(triggersOfJob.contains(trigger2));

    sched.shutdown(true);
  }
  @Override
  public void triggerJob(String jobId) {
    try {
      List<? extends Trigger> existingTriggers =
          sched.getTriggersOfJob(jobKey(jobId, Scheduler.DEFAULT_GROUP));

      if (!existingTriggers.isEmpty()) {
        // Note: we assume that every job has exactly one trigger
        Trigger oldTrigger = existingTriggers.get(0);
        TriggerKey oldTriggerKey = oldTrigger.getKey();
        Trigger newTrigger =
            newTrigger()
                .withIdentity(oldTriggerKey)
                .startAt(getFutureDate(0, TimeUnit.MILLISECONDS))
                .build();

        rescheduleAJob(oldTriggerKey.getName(), oldTriggerKey.getGroup(), newTrigger);
      } else {
        log.error("failed to trigger a job with id={}, job has no trigger", jobId);
      }
    } catch (SchedulerException se) {
      log.error("failed to trigger a job with id={}: {}", jobId, se.getMessage());
      log.debug("Exception", se);
    }
  }
示例#3
0
 @SuppressWarnings("unchecked")
 public List<EndpointDTO> list() {
   List<EndpointDTO> endpointDTOs = Lists.newArrayList();
   try {
     for (String groupName : scheduler.getJobGroupNames()) {
       for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
         JobDetail jobDetail = scheduler.getJobDetail(jobKey);
         List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
         endpointDTOs.add(new EndpointDTO(jobDetail, triggers));
       }
     }
   } catch (SchedulerException e) {
   }
   return endpointDTOs;
 }
示例#4
0
  @Async
  public void runJob(JobDetails jobDetails, Scheduler scheduler)
      throws JobExecutionAlreadyRunningException, JobRestartException,
          JobInstanceAlreadyCompleteException, JobParametersInvalidException,
          SpartanPersistenceException, SchedulerException, ClassNotFoundException {
    Map<String, JobParameter> jobMapParams = new HashMap<String, JobParameter>();
    JobParameter paramMonth = new JobParameter(1l);
    jobMapParams.put("salForMonth", paramMonth);

    JobParameter paramDateTime = new JobParameter(new Date(System.currentTimeMillis()));
    jobMapParams.put("myCurrentTime", paramDateTime);

    JobParameters defaultParams = new JobParameters(jobMapParams);

    JobDataMap newJobData = new JobDataMap(jobMapParams);

    // Creating Job and link to our Job class
    Class jobClass = Class.forName(jobDetails.getBeanName());
    List<String> listOfJob = scheduler.getJobGroupNames();
    if (listOfJob.size() == 0) {
      schdeuleJob(jobClass, scheduler, jobDetails, newJobData);
    } else {
      for (String groupName : scheduler.getJobGroupNames()) {

        for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {

          String jobName = jobKey.getName();
          String jobGroup = jobKey.getGroup();

          // get job's trigger
          List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
          CronTrigger nextFireTime = (CronTrigger) triggers.get(0);
          if (jobDetails.getJobName().equalsIgnoreCase(jobName)
              && !jobDetails
                  .getScheduler()
                  .getSchedulerExpression()
                  .equalsIgnoreCase(nextFireTime.getCronExpression())) {
            scheduler.deleteJob(jobKey);
            schdeuleJob(jobClass, scheduler, jobDetails, newJobData);
          } else if (listOfJob.contains(jobDetails.getJobName())) {

          } else {
            schdeuleJob(jobClass, scheduler, jobDetails, newJobData);
          }
        }
      }
    }
  }
示例#5
0
 /**
  * 获取下次作业触发时间.
  *
  * @return 下次作业触发时间
  */
 public Date getNextFireTime() {
   Date result = null;
   List<? extends Trigger> triggers;
   try {
     triggers = scheduler.getTriggersOfJob(jobDetail.getKey());
   } catch (final SchedulerException ex) {
     return result;
   }
   for (Trigger each : triggers) {
     Date nextFireTime = each.getNextFireTime();
     if (null == nextFireTime) {
       continue;
     }
     if (null == result) {
       result = nextFireTime;
     } else if (nextFireTime.getTime() < result.getTime()) {
       result = nextFireTime;
     }
   }
   return result;
 }
 @Override
 public void startScheduler() {
   final SchedulerDetail schedulerDetail =
       this.schedularWritePlatformService.retriveSchedulerDetail();
   if (schedulerDetail.isSuspended()) {
     schedulerDetail.updateSuspendedState(false);
     this.schedularWritePlatformService.updateSchedulerDetail(schedulerDetail);
     if (schedulerDetail.isExecuteInstructionForMisfiredJobs()) {
       final List<ScheduledJobDetail> scheduledJobDetails =
           this.schedularWritePlatformService.retrieveAllJobs();
       for (final ScheduledJobDetail jobDetail : scheduledJobDetails) {
         if (jobDetail.isTriggerMisfired()) {
           if (jobDetail.isActiveSchedular()) {
             executeJob(jobDetail, SchedulerServiceConstants.TRIGGER_TYPE_CRON);
           }
           final String schedulerName = getSchedulerName(jobDetail);
           final Scheduler scheduler = this.schedulers.get(schedulerName);
           if (scheduler != null) {
             final String key = jobDetail.getJobKey();
             final JobKey jobKey = constructJobKey(key);
             try {
               final List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
               for (final Trigger trigger : triggers) {
                 if (trigger.getNextFireTime() != null
                     && trigger.getNextFireTime().after(jobDetail.getNextRunTime())) {
                   jobDetail.updateNextRunTime(trigger.getNextFireTime());
                 }
               }
             } catch (final SchedulerException e) {
               logger.error(e.getMessage(), e);
             }
           }
           jobDetail.updateTriggerMisfired(false);
           this.schedularWritePlatformService.saveOrUpdate(jobDetail);
         }
       }
     }
   }
 }
  /**
   * Schedules a given job and trigger (both wrapped by a <code>JobSchedulingBundle</code>).
   *
   * @param job job wrapper.
   * @param sched job scheduler.
   * @param localOverWriteExistingJobs locally overwrite existing jobs.
   * @exception SchedulerException if the Job or Trigger cannot be added to the Scheduler, or there
   *     is an internal Scheduler error.
   */
  public void scheduleJob(
      JobSchedulingBundle job, Scheduler sched, boolean localOverWriteExistingJobs)
      throws SchedulerException {
    if ((job != null) && job.isValid()) {
      JobDetail detail = job.getJobDetail();

      JobDetail dupeJ = sched.getJobDetail(detail.getName(), detail.getGroup());

      if ((dupeJ != null) && !localOverWriteExistingJobs) {
        getLog().info("Not overwriting existing job: " + dupeJ.getFullName());
        return;
      }

      if (dupeJ != null) {
        getLog().info("Replacing job: " + detail.getFullName());
      } else {
        getLog().info("Adding job: " + detail.getFullName());
      }

      if (job.getTriggers().size() == 0 && !job.getJobDetail().isDurable()) {
        if (dupeJ == null) {
          throw new SchedulerException(
              "A new job defined without any triggers must be durable: " + detail.getFullName());
        }

        if ((dupeJ.isDurable()
            && (sched.getTriggersOfJob(detail.getName(), detail.getGroup()).length == 0))) {
          throw new SchedulerException(
              "Can't make a durable job without triggers non-durable: " + detail.getFullName());
        }
      }

      sched.addJob(detail, true);

      for (Iterator iter = job.getTriggers().iterator(); iter.hasNext(); ) {
        Trigger trigger = (Trigger) iter.next();

        trigger.setJobName(detail.getName());
        trigger.setJobGroup(detail.getGroup());

        if (trigger.getStartTime() == null) {
          trigger.setStartTime(new Date());
        }

        boolean addedTrigger = false;
        while (addedTrigger == false) {
          Trigger dupeT = sched.getTrigger(trigger.getName(), trigger.getGroup());
          if (dupeT != null) {
            if (getLog().isDebugEnabled()) {
              getLog()
                  .debug(
                      "Rescheduling job: "
                          + detail.getFullName()
                          + " with updated trigger: "
                          + trigger.getFullName());
            }
            if (!dupeT.getJobGroup().equals(trigger.getJobGroup())
                || !dupeT.getJobName().equals(trigger.getJobName())) {
              getLog().warn("Possibly duplicately named triggers in jobs xml file!");
            }
            sched.rescheduleJob(trigger.getName(), trigger.getGroup(), trigger);
          } else {
            if (getLog().isDebugEnabled()) {
              getLog()
                  .debug(
                      "Scheduling job: "
                          + detail.getFullName()
                          + " with trigger: "
                          + trigger.getFullName());
            }

            try {
              sched.scheduleJob(trigger);
            } catch (ObjectAlreadyExistsException e) {
              if (getLog().isDebugEnabled()) {
                getLog()
                    .debug(
                        "Adding trigger: "
                            + trigger.getFullName()
                            + " for job: "
                            + detail.getFullName()
                            + " failed because the trigger already existed.  "
                            + "This is likely due to a race condition between multiple instances "
                            + "in the cluster.  Will try to reschedule instead.");
              }
              continue;
            }
          }
          addedTrigger = true;
        }
      }

      addScheduledJob(job);
    }
  }
示例#8
0
 public RunTimeJobDetail getJobDetails(String group, String name) throws SchedulerException {
   JobKey jobKey = new JobKey(name, group);
   return new RunTimeJobDetail()
       .setJobDetail(quartzScheduler.getJobDetail(jobKey))
       .setTriggers(quartzScheduler.getTriggersOfJob(jobKey));
 }