Exemple #1
0
 public void execute(JobExecutionContext context) throws JobExecutionException {
   String taskName = context.getTrigger().getKey().getName();
   logger.info(
       "任务[ " + taskName + " ]启动于 " + DateToString(context.getFireTime(), "yyyy-MM-dd HH:mm:ss"));
   try {
     doTask();
   } catch (Exception e) {
     throw new JobExecutionException(e);
   } finally {
     logger.info(
         "任务[ "
             + taskName
             + " ]下次将于"
             + DateToString(context.getNextFireTime(), "yyyy-MM-dd HH:mm:ss")
             + " 启动");
   }
 }
Exemple #2
0
  @Override
  protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {

    // The job data map is available through the JobExecutionContext
    // (passed to you at execution time)
    JobDataMap jobDataMap = ctx.getJobDetail().getJobDataMap();

    try {
      // Retrieve the last date when the job was run
      Date lastDateRun = ctx.getPreviousFireTime();

      // Job was run previously
      if (lastDateRun != null) {
        //				logger.debug("Last date run: " + sdf.format(lastDateRun));
        System.out.println("Last date run: " + sdf.format(lastDateRun));
        // Retrieve the number of times this job has been attempted
        int refireCount = ctx.getRefireCount();

        if (refireCount > 0) {
          //					logger.debug("Total attempts: " + refireCount);
          System.out.println("Total attempts: " + refireCount);
        }
      } else {
        // Job is run for the first time
        //				logger.debug("Job is run for the first time");
        System.out.println("Job is run for the first time");
      }

      // Do the actual work
      //			logger.debug("Delegating work to worker");
      System.out.println("Delegating work to worker");
      worker.work();

      // Retrieve the next date when the job will be run
      String nextDateRun = sdf.format(ctx.getNextFireTime());

      //			logger.debug("Next date run: " + nextDateRun);
      System.out.println("Next date run: " + nextDateRun);

    } catch (Exception e) {
      //			logger.error("Unexpected exception" , e);
      e.printStackTrace();
      throw new JobExecutionException("Unexpected exception", e, true);
    }
  }
  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    try {

      log.info(
          "Execute: Details : "
              + " at : "
              + new Date()
              + " : Previous Fire time : "
              + context.getPreviousFireTime()
              + " : Next Fire time : "
              + context.getNextFireTime()
              + " : Scheduled Fire time : "
              + context.getScheduledFireTime()
              + " : Fire Instance ID : "
              + context.getFireInstanceId()
              + " : Job Run Time : "
              + context.getJobRunTime()
              + " : Refire Count : "
              + context.getRefireCount()
              + " : Fire Time : "
              + context.getFireTime());

      String fileName = context.getTrigger().getKey().getName();
      File file = new File(fileName + ".txt");

      // if file doesnt exists, then create it
      if (!file.exists()) {
        file.createNewFile();
      }

      // true = append file
      FileWriter fileWritter = new FileWriter(file.getName(), true);
      BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
      bufferWritter.write(new Date().toString() + "\n");
      bufferWritter.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  @SuppressWarnings("unchecked")
  public void jobToBeExecuted(JobExecutionContext context) {
    ALNTLogger.info(this.getClass().getName(), "jobToBeExecuted()", "Begin");
    try {
      ISchedulerConfigService schedulerConfigService =
          (ISchedulerConfigService) ServiceLocator.findService("schedulerConfigService");

      JobDetail jobDetails = context.getJobDetail();
      Long id = (Long) jobDetails.getJobDataMap().get("JOB_ID");
      String jobPgmName = (String) jobDetails.getJobDataMap().get("JOB_NAME");

      String triggerGroup = context.getTrigger().getGroup();
      boolean recoveringJob = false;
      JobStatus jobStatus = null;
      if (!StringUtils.isEmpty(triggerGroup) && triggerGroup.equals("RECOVERING_JOBS")) {
        recoveringJob = true;
        jobDetails.getJobDataMap().put(SchedulerUtil.RECOVERING_JOB, Boolean.TRUE);

        List<JobStatus> jobStatusList = null;
        try {
          jobStatusList =
              schedulerConfigService.loadJobStatus(
                  jobDetails.getJobDataMap().getLongValue("JOB_ID"));
          if (null != jobStatusList && jobStatusList.size() > 0) {
            jobStatus = jobStatusList.get(jobStatusList.size() - 1);
            jobDetails
                .getJobDataMap()
                .put(SchedulerUtil.RECOVERING_JOB_STATUS_ID, jobStatus.getId());
            jobStatus.setJobStatus(CommonConstants.JOB_STATUS_RUNNING);
          }
        } catch (Exception ex) {
          ALNTLogger.error(this.getClass().getName(), "jobToBeExecuted", ex);
        }
      }

      if (jobStatus == null) {
        jobStatus = new JobStatus();
        jobStatus.setJobId(id);
        Date nextFireTime = context.getNextFireTime();
        jobStatus.setNextFireTime(nextFireTime);
        jobStatus.setJobName(jobPgmName);
        jobStatus.setCreationDate(new Date());
        jobStatus.setJobStatus(CommonConstants.JOB_STATUS_RUNNING);
      }

      Job job = context.getJobInstance();
      if (job instanceof IJobsWithResult) {
        IJobsWithResult jobWithResult = (IJobsWithResult) job;
        JobResultWriter writer = new JobResultWriter();
        writer.setCreateDate(jobStatus.getCreationDate());
        writer.setJobId(id);
        writer.init();
        jobWithResult.setResultWriter(writer);
      }
      if (jobDetails.getJobDataMap().containsKey(SchedulerUtil.RETRYING_JOB)
          && jobDetails.getJobDataMap().containsKey(SchedulerUtil.FAILED_JOB_STATUS_ID)
          && jobDetails.getJobDataMap().containsKey(SchedulerUtil.RETRYING_JOB_STATUS_ID)) {
        if (jobDetails.getJobDataMap().getBoolean(SchedulerUtil.RETRYING_JOB)) {
          jobStatus.setOriginalFailedId(
              jobDetails.getJobDataMap().getLong(SchedulerUtil.FAILED_JOB_STATUS_ID));
          jobStatus.setRetryForId(
              jobDetails.getJobDataMap().getLong(SchedulerUtil.RETRYING_JOB_STATUS_ID));
        }
      }

      jobStatus = schedulerConfigService.saveJobStatus(jobStatus);

      jobDetails.getJobDataMap().put("JobStatus_ID", jobStatus.getId());
      if (recoveringJob) {

      } else if (jobStatus.getRetryForId() != null) {
        JobStatus retryingForJobStatus =
            schedulerConfigService.loadJobStatusByStatusId(jobStatus.getRetryForId());
        if (retryingForJobStatus != null) {
          // get the job status object that simply says retrying and append it with new job status
          // id
          retryingForJobStatus.setJobStatus(
              CommonConstants.JOB_STATUS_RETRIED + " - " + jobStatus.getId());
          schedulerConfigService.saveJobStatus(retryingForJobStatus);
        }
      }

      ALNTLogger.info(this.getClass().getName(), "jobToBeExecuted()", "End");
    } catch (ALNTSystemException e) {
      ALNTLogger.error(this.getClass().getName(), "jobToBeExecuted()", "Error ::" + e.getMessage());
    } catch (ALNTApplicationException e) {
      ALNTLogger.error(this.getClass().getName(), "jobToBeExecuted", "Error ::" + e.getMessage());
    }
  }
  public void jobWasExecuted(JobExecutionContext context, JobExecutionException arg1) {
    SchedulerMailUtil mailUtil = new SchedulerMailUtil();
    ALNTLogger.info(this.getClass().getName(), "jobWasExecuted()", "Begin");
    try {
      ISchedulerConfigService schedulerConfigService =
          (ISchedulerConfigService) ServiceLocator.findService("schedulerConfigService");
      Job job = context.getJobInstance();
      if (job instanceof IJobsWithResult) {
        IJobsWithResult jobWithResult = (IJobsWithResult) job;
        JobResultWriter writer = jobWithResult.getResultWriter();
        if (writer != null) {
          writer.getLogWriter().flush();
          writer.getLogWriter().close();
          writer.getResultWriter().flush();
          writer.getResultWriter().close();
        }
      }
      Object jobId = context.getJobDetail().getJobDataMap().get("JOB_ID");
      Object id = context.getJobDetail().getJobDataMap().get("JobStatus_ID");
      String jobPgmName = (String) context.getJobDetail().getJobDataMap().get("JOB_NAME");
      ScheduledJobs scheduledJobs =
          schedulerConfigService.loadScheduledJob(new Long(jobId.toString()));
      ALNTLogger.info(getName(), "Got NotificationDetail object from ScheduledJobs");

      // Getting notification object to send the notification email to user
      scheduledNotificationDetail = scheduledJobs.getScheduledNotificationDetail();

      JobStatus jobStatus =
          schedulerConfigService.loadJobStatus(new Long(jobId.toString()), new Long(id.toString()));
      if (CommonConstants.SCHEDULE_IMMEDIATE.equalsIgnoreCase(scheduledJobs.getInterval())) {
        scheduledJobs.setActiveStatus(false);
      } else if (CommonConstants.SCHEDULE_ONCE.equalsIgnoreCase(scheduledJobs.getInterval())) {
        scheduledJobs.setActiveStatus(false);
      } else if (scheduledJobs.getInterval().startsWith(CommonConstants.SCHEDULE_PERIODICALLY)) {
        if (null == context.getNextFireTime()) {
          scheduledJobs.setActiveStatus(false);
        }
      }

      if (CommonConstants.JOB_STATUS_CANCELING.equalsIgnoreCase(jobStatus.getJobStatus())) {
        scheduledJobs.setActiveStatus(false);
        jobStatus.setJobStatus(CommonConstants.JOB_STATUS_CANCELED);

      } else {
        jobStatus.setJobStatus(CommonConstants.JOB_STATUS_COMPLETED);
        if (arg1 != null) {
          jobStatus.setJobStatus(CommonConstants.JOB_STATUS_FAILED);
        } else if (context
            .getJobDetail()
            .getJobDataMap()
            .containsKey(CommonConstants.JOB_STATUS_SKIPPED)) {
          jobStatus.setJobStatus(CommonConstants.JOB_STATUS_SKIPPED);
          context.getJobDetail().getJobDataMap().remove(CommonConstants.JOB_STATUS_SKIPPED);
        }
        if (context.getJobDetail() != null
            && context.getJobDetail().getJobDataMap() != null
            && context
                .getJobDetail()
                .getJobDataMap()
                .containsKey(CommonConstants.NO_VALID_FEED_FILE_EXISTS)) {
          jobStatus.setJobStatus(
              CommonConstants.JOB_STATUS_FAILED + "- " + CommonConstants.NO_VALID_FEED_FILE_EXISTS);
          context.getJobDetail().getJobDataMap().remove(CommonConstants.NO_VALID_FEED_FILE_EXISTS);
        }
        // completionTime=context.getFireTime();

        JobStage jobStage =
            schedulerConfigService.loadJobStage(
                jobStatus.getOriginalFailedId() == null
                    ? jobStatus.getId()
                    : jobStatus.getOriginalFailedId());
        if (jobStage != null) {
          jobStatus.setLastKnowStage(jobStage.getJobStage());
        }
      }

      // Sending notification email to user with status of current job with defined parameters or
      // with standard parameters
      // If the notification has not been configured for current running job then
      // scheduledNotificationDetail object will be null
      // so we are checking for that the notification has been configured for this or not
      if (scheduledNotificationDetail != null) {
        if (job instanceof IJobWithExtendedMailSubstVar) {
          Map<String, String> mapParams =
              ((IJobWithExtendedMailSubstVar) job).getMailSubstVarValues();
          mapParams.putAll(this.getStandardJobParams(scheduledJobs));
          mailUtil.sendMail(scheduledNotificationDetail, jobStatus.getJobStatus(), mapParams);
        } else {
          mailUtil.sendMail(
              scheduledNotificationDetail,
              jobStatus.getJobStatus(),
              this.getStandardJobParams(scheduledJobs));
        }
      }

      jobStatus.setCompleteTime(new Date());
      jobStatus.setJobName(jobPgmName);

      schedulerConfigService.saveScheduledJobWithoutScheduleJob(scheduledJobs);
      schedulerConfigService.saveJobStatus(jobStatus);

      ALNTLogger.info(this.getClass().getName(), "jobWasExecuted()", "End");
    } catch (ALNTSystemException e) {
      ALNTLogger.error(this.getClass().getName(), "jobWasExecuted()", "Error ::" + e.getMessage());
    } catch (ALNTApplicationException e) {
      ALNTLogger.error(this.getClass().getName(), "jobWasExecuted()", ":Error ::" + e.getMessage());
    }
  }
Exemple #6
0
  public void execute(JobExecutionContext jec) throws JobExecutionException {

    try {
      Stripersist.requestInit();
      EntityManager em = Stripersist.getEntityManager();

      StringBuilder monitoringFailures = new StringBuilder();

      int online = 0, offline = 0;

      // TODO: where monitoringEnabled = true...
      for (GeoService gs : (List<GeoService>) em.createQuery("from GeoService").getResultList()) {

        String debugMsg =
            String.format(
                "%s service %s (#%d) with URL: %s",
                gs.getProtocol(), gs.getName(), gs.getId(), gs.getUrl());
        try {

          if (isInterrupted()) {
            log.info("Interrupted, ending monitoring job");
            return;
          }

          gs.checkOnline();
          online++;
          gs.setMonitoringStatusOK(true);
          log.debug("ONLINE: " + debugMsg);
        } catch (Exception e) {
          gs.setMonitoringStatusOK(false);
          offline++;
          log.debug("OFFLINE: " + debugMsg);
          if (log.isTraceEnabled()) {
            log.trace("Exception", e);
          }
          String message = e.toString();
          Throwable cause = e.getCause();
          while (cause != null) {
            message += "; " + cause.toString();
            cause = cause.getCause();
          }
          monitoringFailures.append(
              String.format(
                  "%s service %s (#%d)\nURL: %s\nFout: %s\n\n",
                  gs.getProtocol(), gs.getName(), gs.getId(), gs.getUrl(), message));
        }
      }

      em.getTransaction().commit();

      log.info(
          String.format(
              "Total services %d, online: %d, offline: %d, runtime: %d s",
              online + offline, online, offline, jec.getJobRunTime() / 1000));

      if (offline > 0) {

        Set emails = new HashSet();
        for (User admin :
            (List<User>)
                em.createQuery(
                        "select u from User u "
                            + "join u.groups g "
                            + "where g.name = '"
                            + Group.SERVICE_ADMIN
                            + "' ")
                    .getResultList()) {
          emails.add(admin.getDetails().get(User.DETAIL_EMAIL));
        }
        emails.remove(null);

        if (!emails.isEmpty()) {
          StringBuilder mail = new StringBuilder();

          SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyy HH:mm:ss");
          mail.append(
              String.format(
                  "Bij een controle op %s zijn in het gegevensregister %d services gevonden waarbij fouten zijn geconstateerd.\n"
                      + "\nDe volgende controle zal worden uitgevoerd op %s.\nHieronder staat de lijst met probleemservices:\n\n",
                  f.format(jec.getFireTime()), offline, f.format(jec.getNextFireTime())));
          mail.append(monitoringFailures);

          mail(jec, emails, offline + " services zijn offline bij controle", mail.toString());
        }
      }
    } catch (Exception e) {
      log.error("Error", e);
    } finally {
      Stripersist.requestComplete();
    }
  }