/**
  * Add the given trigger to the Scheduler, if it doesn't already exist. Overwrites the trigger in
  * any case if "overwriteExistingJobs" is set.
  *
  * @param trigger the trigger to add
  * @return {@code true} if the trigger was actually added, {@code false} if it already existed
  *     before
  * @see #setOverwriteExistingJobs
  */
 private boolean addTriggerToScheduler(Trigger trigger) throws SchedulerException {
   boolean triggerExists = (getScheduler().getTrigger(trigger.getKey()) != null);
   if (!triggerExists || this.overwriteExistingJobs) {
     // Check if the Trigger is aware of an associated JobDetail.
     JobDetail jobDetail = (JobDetail) trigger.getJobDataMap().remove("jobDetail");
     if (jobDetail != null) {
       // Automatically register the JobDetail too.
       if (!this.jobDetails.contains(jobDetail) && addJobToScheduler(jobDetail)) {
         this.jobDetails.add(jobDetail);
       }
     }
     if (!triggerExists) {
       try {
         getScheduler().scheduleJob(trigger);
       } catch (ObjectAlreadyExistsException ex) {
         if (logger.isDebugEnabled()) {
           logger.debug(
               "Unexpectedly found existing trigger, assumably due to cluster race condition: "
                   + ex.getMessage()
                   + " - can safely be ignored");
         }
         if (this.overwriteExistingJobs) {
           getScheduler().rescheduleJob(trigger.getKey(), trigger);
         }
       }
     } else {
       getScheduler().rescheduleJob(trigger.getKey(), trigger);
     }
     return true;
   } else {
     return false;
   }
 }
  /** @see org.quartz.JobListener#jobWasExecuted(JobExecutionContext, JobExecutionException) */
  public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {

    Trigger trigger = context.getTrigger();

    Object[] args = null;

    Object oResult = context.getResult();
    String result = showJobDataMap(oResult);

    if (jobException != null) {

      String errMsg = jobException.getMessage();
      args =
          new Object[] {
            context.getJobDetail().getKey().getName(),
            context.getJobDetail().getKey().getGroup(),
            new java.util.Date(),
            trigger.getKey().getName(),
            trigger.getKey().getGroup(),
            trigger.getPreviousFireTime(),
            trigger.getNextFireTime(),
            Integer.valueOf(context.getRefireCount()),
            context.getFireInstanceId(),
            result,
            errMsg
          };

      try {
        insertJobDetail(this.getNonManagedTXConnection(), context);
        getLog().info(MessageFormat.format(getJobFailedMessage(), args)); // without exception trace
        //				getLog().info(MessageFormat.format(getJobFailedMessage(), args),
        //				jobException);
      } catch (Exception e) {
        getLog().error(MessageFormat.format(getJobFailedMessage(), args, e));
      }
    } else {

      args =
          new Object[] {
            context.getJobDetail().getKey().getName(),
            context.getJobDetail().getKey().getGroup(),
            new java.util.Date(),
            trigger.getKey().getName(),
            trigger.getKey().getGroup(),
            trigger.getPreviousFireTime(),
            trigger.getNextFireTime(),
            Integer.valueOf(context.getRefireCount()),
            context.getFireInstanceId(),
            result
          };

      try {
        insertJobDetail(this.getNonManagedTXConnection(), context);
        getLog().info(MessageFormat.format(getJobSuccessMessage(), args));
      } catch (Exception e) {
        getLog().error(MessageFormat.format(getJobSuccessMessage(), args, e));
      }
    }
  }
  protected void update(
      Scheduler scheduler,
      com.liferay.portal.kernel.scheduler.Trigger trigger,
      StorageType storageType)
      throws Exception {

    Trigger quartzTrigger = getQuartzTrigger(trigger, storageType);

    if (quartzTrigger == null) {
      return;
    }

    TriggerKey triggerKey = quartzTrigger.getKey();

    if (scheduler.getTrigger(triggerKey) != null) {
      scheduler.rescheduleJob(triggerKey, quartzTrigger);
    } else {
      JobKey jobKey = quartzTrigger.getJobKey();

      JobDetail jobDetail = scheduler.getJobDetail(jobKey);

      if (jobDetail == null) {
        return;
      }

      synchronized (this) {
        scheduler.deleteJob(jobKey);
        scheduler.scheduleJob(jobDetail, quartzTrigger);
      }

      updateJobState(scheduler, jobKey, TriggerState.NORMAL, 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);
    }
  }
예제 #5
0
 protected void updateScheduledRouteDetails(
     Action action, JobDetail jobDetail, Trigger trigger, Route route) throws Exception {
   ScheduledRouteDetails scheduledRouteDetails = getScheduledRouteDetails(route.getId());
   if (action == Action.START) {
     scheduledRouteDetails.setStartJobKey(jobDetail.getKey());
     scheduledRouteDetails.setStartTriggerKey(trigger.getKey());
   } else if (action == Action.STOP) {
     scheduledRouteDetails.setStopJobKey(jobDetail.getKey());
     scheduledRouteDetails.setStopTriggerKey(trigger.getKey());
   } else if (action == Action.SUSPEND) {
     scheduledRouteDetails.setSuspendJobKey(jobDetail.getKey());
     scheduledRouteDetails.setSuspendTriggerKey(trigger.getKey());
   } else if (action == Action.RESUME) {
     scheduledRouteDetails.setResumeJobKey(jobDetail.getKey());
     scheduledRouteDetails.setResumeTriggerKey(trigger.getKey());
   }
 }
예제 #6
0
  public void triggerFired(Trigger trigger, JobExecutionContext jobExecutionContext) {

    eventManager.createTriggerEvent(
        TriggerEvent.TRIGGER_EVENT_TYPE.FIRED,
        jobExecutionContext.getJobDetail().getKey(),
        trigger.getKey(),
        new Date(),
        "Trigger fired",
        getServerId());
  }
  /** @see org.quartz.JobListener#jobToBeExecuted(JobExecutionContext) */
  public void jobToBeExecuted(JobExecutionContext context) {

    try {
      ForEachListener forEachListener =
          new TrackNRestartListener(
              dataSource,
              tablePrefix,
              this.getName(),
              scheduler.getSchedulerName(),
              context.getJobDetail().getKey().getGroup(),
              context.getJobDetail().getKey().getName(),
              context.getFireInstanceId());
      context.getJobDetail().getJobDataMap().put(FOR_EACH_LISTENER, forEachListener);
    } catch (Exception e) {
      TrackNRestartMessageKind.ETNRPLUGIN0002.format(e);
      // getLog().error("Unexpected exception.",e);
    }

    Trigger trigger = context.getTrigger();

    JobDetail jobDetail = context.getJobDetail();
    JobDataMap jobDataMap = jobDetail.getJobDataMap();

    String params = "";
    for (Iterator<Entry<String, Object>> iterator = jobDataMap.entrySet().iterator();
        iterator.hasNext(); ) {
      Entry<String, Object> entry = (Entry<String, Object>) iterator.next();
      params += entry.getKey() + "=" + entry.getValue();
      if (iterator.hasNext()) {
        params += ", ";
      }
    }

    Object[] args = {
      jobDetail.getKey().getName(),
      jobDetail.getKey().getGroup(),
      new java.util.Date(),
      trigger.getKey().getName(),
      trigger.getKey().getGroup(),
      trigger.getPreviousFireTime(),
      trigger.getNextFireTime(),
      Integer.valueOf(context.getRefireCount()),
      context.getFireInstanceId(),
      params
    };

    try {

      // TODO : not for JobToBeFired ?
      //			insertJobDetail(this.getNonManagedTXConnection(), context);
      getLog().info(MessageFormat.format(getJobToBeFiredMessage(), args));
    } catch (Exception e) {
      getLog().error(MessageFormat.format(getJobToBeFiredMessage(), args, e));
    }
  }
  /**
   * @param context
   * @see org.quartz.JobListener#jobToBeExecuted(JobExecutionContext) Called by the Scheduler when a
   *     JobDetail is about to be executed (an associated Trigger has occurred)
   */
  @Override
  public void jobToBeExecuted(JobExecutionContext context) {
    try {
      /*if (!getLog().isInfoEnabled()) {
      return;
      }*/
      String ipAddress = getIpAddress();
      Trigger trigger = context.getTrigger();

      Object[] args = {
        context.getFireInstanceId(),
        context.getJobDetail().getKey().getName(),
        context.getJobDetail().getKey().getGroup(),
        jobDataMapToString(context.getJobDetail().getJobDataMap()),
        new java.util.Date(),
        trigger.getKey().getName(),
        trigger.getKey().getGroup(),
        trigger.getPreviousFireTime() != null ? trigger.getPreviousFireTime() : new Date(0),
        trigger.getNextFireTime() != null ? trigger.getNextFireTime() : new Date(0),
        Integer.toString(context.getRefireCount()),
        "",
        context.getScheduler().getSchedulerInstanceId(),
        context.getScheduler().getSchedulerName(),
        ipAddress != null ? ipAddress : "",
        "RUNNING",
        "LoggingJobHistoryPluginCustom",
        "INFO"
      };

      // update the job data map of the job to be executed with the fire instance id (to be used to
      // retrieve the running job for setting/getting the job progress %)
      // the job data map is not updated on the scheduler, but only on the running instance of the
      // job, because the id is related to it
      /*JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
      JSONArray jsonarray = null;
      JSONParser parser = new JSONParser();
      if (jobDataMap.containsKey("#processParameters")) {
          jsonarray = (JSONArray) parser.parse(jobDataMap.getString("#processParameters"));
      } else {
          jsonarray = new JSONArray();
      }
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("fireInstanceId", context.getFireInstanceId());
      jsonarray.add(jsonObject);
      context.getJobDetail().getJobDataMap().put("#processParameters", jsonarray.toString());*/

      // getLog().info(MessageFormat.format(getJobToBeFiredMessage(), args));
      // log data and set progress value as null because it has not to be updated in the database
      // row
      logToDatabase(args, MessageFormat.format(getJobToBeFiredMessage(), args), true, null);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /**
  * Trigger被激发 它关联的job即将被运行 Called by the Scheduler when a Trigger has fired, and it's associated
  * JobDetail is about to be executed.
  *
  * @param trigger
  * @param context
  */
 public void triggerFired(Trigger trigger, JobExecutionContext context) {
   TriggerKey triggerKey = trigger.getKey();
   String name = triggerKey.getName();
   String group = triggerKey.getGroup();
   System.out.println(
       "Trigger监听器:QuartzTriggerListener.triggerFired(),[name = "
           + name
           + ",group = "
           + group
           + "]");
 }
예제 #10
0
 @Override
 public void triggerComplete(
     Trigger trigger,
     JobExecutionContext context,
     CompletedExecutionInstruction triggerInstructionCode) {
   eventManager.createTriggerEvent(
       TriggerEvent.TRIGGER_EVENT_TYPE.COMPLETE,
       context.getJobDetail().getKey(),
       trigger.getKey(),
       new Date(),
       "Trigger complete",
       getServerId());
 }
예제 #11
0
  public void scheduleRoute(Action action, Route route) throws Exception {
    JobDetail jobDetail = createJobDetail(action, route);
    Trigger trigger = createTrigger(action, route);
    updateScheduledRouteDetails(action, jobDetail, trigger, route);

    loadCallbackDataIntoSchedulerContext(jobDetail, action, route);
    getScheduler().scheduleJob(jobDetail, trigger);

    if (LOG.isInfoEnabled()) {
      LOG.info(
          "Scheduled trigger: {} for action: {} on route {}",
          new Object[] {trigger.getKey(), action, route.getId()});
    }
  }
  /** @see org.quartz.JobListener#jobExecutionVetoed(org.quartz.JobExecutionContext) */
  public void jobExecutionVetoed(JobExecutionContext context) {

    Trigger trigger = context.getTrigger();

    Object[] args = {
      context.getJobDetail().getKey().getName(),
      context.getJobDetail().getKey().getGroup(),
      new java.util.Date(),
      trigger.getKey().getName(),
      trigger.getKey().getGroup(),
      trigger.getPreviousFireTime(),
      trigger.getNextFireTime(),
      Integer.valueOf(context.getRefireCount())
    };

    try {
      // TODO : not for jobExecutionVetoed ?
      //			insertJobDetail(this.getNonManagedTXConnection(), context);
      getLog().info(MessageFormat.format(getJobWasVetoedMessage(), args));
    } catch (Exception e) {
      getLog().error(MessageFormat.format(getJobWasVetoedMessage(), args, e));
    }
  }
  /**
   * @param context
   * @see org.quartz.JobListener#jobExecutionVetoed(org.quartz.JobExecutionContext) Called by the
   *     Scheduler when a JobDetail was about to be executed (an associated Trigger has occurred),
   *     but a TriggerListener vetoed it's execution
   */
  @Override
  public void jobExecutionVetoed(JobExecutionContext context) {
    try {
      /*if (!getLog().isInfoEnabled()) {
      return;
      }*/
      String ipAddress = getIpAddress();
      Trigger trigger = context.getTrigger();

      Object[] args = {
        context.getFireInstanceId(),
        context.getJobDetail().getKey().getName(),
        context.getJobDetail().getKey().getGroup(),
        jobDataMapToString(context.getJobDetail().getJobDataMap()),
        new java.util.Date(),
        trigger.getKey().getName(),
        trigger.getKey().getGroup(),
        trigger.getPreviousFireTime() != null ? trigger.getPreviousFireTime() : new Date(0),
        trigger.getNextFireTime() != null ? trigger.getNextFireTime() : new Date(0),
        Integer.toString(context.getRefireCount()),
        "",
        context.getScheduler().getSchedulerInstanceId(),
        context.getScheduler().getSchedulerName(),
        ipAddress != null ? ipAddress : "",
        "VETOED",
        "LoggingJobHistoryPluginCustom",
        "INFO"
      };
      // getLog().info(MessageFormat.format(getJobWasVetoedMessage(), args));
      // log data and set progress value as null because it has not to be updated in the database
      // row
      logToDatabase(args, MessageFormat.format(getJobWasVetoedMessage(), args), true, null);
    } catch (SchedulerException | SQLException e) {
      e.printStackTrace();
    }
  }
 public void jobScheduled(Trigger trigger) {
   getLog().debug("Trigger " + trigger.getKey() + " scheduled Job " + trigger.getJobKey() + ".");
 }
 public void submit(final Scheduler scheduler) throws SchedulerException {
   scheduler.rescheduleJob(trigger.getKey(), getTrigger());
 }
  /**
   * @param context
   * @param jobException
   * @see org.quartz.JobListener#jobWasExecuted(JobExecutionContext, JobExecutionException) Called
   *     by the Scheduler after a JobDetail has been executed, and be for the associated Trigger's
   *     triggered method has been called
   */
  @Override
  public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
    try {
      String ipAddress = getIpAddress();
      Trigger trigger = context.getTrigger();

      Object[] args;

      if (jobException != null) {
        /*if (!getLog().isWarnEnabled()) {
        return;
        }*/

        String errMsg = jobException.getMessage();
        args =
            new Object[] {
              context.getFireInstanceId(),
              context.getJobDetail().getKey().getName(),
              context.getJobDetail().getKey().getGroup(),
              jobDataMapToString(context.getJobDetail().getJobDataMap()),
              new java.util.Date(),
              trigger.getKey().getName(),
              trigger.getKey().getGroup(),
              trigger.getPreviousFireTime() != null ? trigger.getPreviousFireTime() : new Date(0),
              trigger.getNextFireTime() != null ? trigger.getNextFireTime() : new Date(0),
              Integer.toString(context.getRefireCount()),
              errMsg,
              context.getScheduler().getSchedulerInstanceId(),
              context.getScheduler().getSchedulerName(),
              ipAddress != null ? ipAddress : "",
              "FAILED",
              "LoggingJobHistoryPluginCustom",
              "INFO"
            };
        // getLog().warn(MessageFormat.format(getJobFailedMessage(), args), jobException);
        // log data and set progress value as null because it has not to be updated in the database
        // row
        logToDatabase(args, MessageFormat.format(getJobFailedMessage(), args), true, null);
      } else {
        /*if (!getLog().isInfoEnabled()) {
        return;
        }*/

        String result = String.valueOf(context.getResult());
        args =
            new Object[] {
              context.getFireInstanceId(),
              context.getJobDetail().getKey().getName(),
              context.getJobDetail().getKey().getGroup(),
              jobDataMapToString(context.getJobDetail().getJobDataMap()),
              new java.util.Date(),
              trigger.getKey().getName(),
              trigger.getKey().getGroup(),
              trigger.getPreviousFireTime() != null ? trigger.getPreviousFireTime() : new Date(0),
              trigger.getNextFireTime() != null ? trigger.getNextFireTime() : new Date(0),
              Integer.toString(context.getRefireCount()),
              result, // truncateResult(result) truncate result if too long to insert in the
                      // database
              context.getScheduler().getSchedulerInstanceId(),
              context.getScheduler().getSchedulerName(),
              ipAddress != null ? ipAddress : "",
              "SUCCESS",
              "LoggingJobHistoryPluginCustom",
              "INFO"
            };
        // getLog().info(MessageFormat.format(getJobSuccessMessage(), args));
        // log data and set progress value as 100 because the job completed successfully
        logToDatabase(args, MessageFormat.format(getJobSuccessMessage(), args), true, "100");
      }
    } catch (SQLException | SchedulerException e) {
      e.printStackTrace();
    }
  }
 public void triggerFinalized(Trigger trigger) {
   getLog().debug("Trigger " + trigger.getKey() + " finalized.");
 }