Exemplo n.º 1
0
 @Override
 public void execute(JobExecutionContext context) throws JobExecutionException {
   Task task = (Task) context.getJobDetail().getJobDataMap().get(QuartzShedulerManager.TASK);
   task.execute(
       (Map<String, Object>)
           context.getJobDetail().getJobDataMap().get(QuartzShedulerManager.TASK_PARAM));
 }
Exemplo n.º 2
0
  /** Ejecución del trabajo lanzar RSS */
  public void execute(JobExecutionContext context) throws JobExecutionException {

    String usuario = (String) context.getJobDetail().getJobDataMap().get(CtesPlanificador.USUARIO);

    /* Añadimos la seguridad al proceso */
    log("Usuario que lanza la tarea: " + usuario);
    boolean contextoCargado = Autenticar.cargarContextoSeguridad(usuario);

    if (!contextoCargado) {
      log.error("ERROR: No han cargado los datos en el contexto de seguridad");
      return;
    }

    log(
        "Informes portada: "
            + context.getJobDetail().getFullName()
            + " ejecutandose a las "
            + new Date());

    try {
      SrvPlanificadorService servicio = ServiceLocator.instance().getSrvPlanificadorService();
      servicio.informesPortada();
      log("Se han generado los informes de portada");
    } catch (Exception e) {
      JobExecutionException excepcion =
          new JobExecutionException("Error: No se ha podido realizar los Informes de portada ", e);

      log.error("Error " + excepcion);

      /* Se lanza el error */
      throw excepcion;
    }
  }
Exemplo n.º 3
0
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
    AbstractMessageReceiver receiver =
        (AbstractMessageReceiver) map.get(QuartzMessageReceiver.QUARTZ_RECEIVER_PROPERTY);
    Object payload =
        jobExecutionContext.getJobDetail().getJobDataMap().get(QuartzConnector.PROPERTY_PAYLOAD);

    try {
      if (payload == null) {
        String ref =
            jobExecutionContext
                .getJobDetail()
                .getJobDataMap()
                .getString(QuartzConnector.PROPERTY_PAYLOAD_REFERENCE);
        // for backward compatibility check the old payload Class property too
        if (ref == null) {
          ref =
              jobExecutionContext
                  .getJobDetail()
                  .getJobDataMap()
                  .getString(QuartzConnector.PROPERTY_PAYLOAD_CLASS_NAME);
        }
        try {
          payload = MuleManager.getInstance().getContainerContext().getComponent(ref);
        } catch (ObjectNotFoundException e) {
          logger.warn("There is no payload attached to this quartz job. Sending Null payload");
          payload = new NullPayload();
        }
      }
      receiver.routeMessage(new MuleMessage(receiver.getConnector().getMessageAdapter(payload)));
    } catch (Exception e) {
      receiver.handleException(e);
    }
  }
 protected void makeAuditRecord(
     final float time, final String messageType, final JobExecutionContext jobExecutionContext) {
   if (jobExecutionContext != null && jobExecutionContext.getJobDetail() != null) {
     final JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
     AuditHelper.audit(
         PentahoSessionHolder.getSession() != null
             ? PentahoSessionHolder.getSession().getId()
             : null,
         jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONUSER) != null
             ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONUSER).toString()
             : null,
         jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_STREAMPROVIDER) != null
             ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_STREAMPROVIDER).toString()
             : null,
         jobExecutionContext.getJobDetail().getJobClass() != null
             ? jobExecutionContext.getJobDetail().getJobClass().getName()
             : null,
         jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONID) != null
             ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONID).toString()
             : null,
         messageType,
         jobDataMap.get("lineage-id") != null ? jobDataMap.get("lineage-id").toString() : null,
         null,
         time,
         null); //$NON-NLS-1$
   }
 }
Exemplo n.º 5
0
  /**
   * Called by the <code>{@link org.quartz.Scheduler}</code> when a <code>{@link org.quartz.Trigger}
   * </code> fires that is associated with the <code>Job</code>.
   *
   * @throws JobExecutionException if there is an exception while executing the job.
   */
  public void execute(JobExecutionContext context) throws JobExecutionException {

    // This job simply prints out its job name and the
    // date and time that it is running
    JobKey jobKey = context.getJobDetail().getKey();

    // Grab and print passed parameters
    JobDataMap data = context.getJobDetail().getJobDataMap();
    String favoriteColor = data.getString(FAVORITE_COLOR);
    int count = data.getInt(EXECUTION_COUNT);
    _log.info(
        "ColorJob: "
            + jobKey
            + " executing at "
            + new Date()
            + "\n"
            + "  favorite color is "
            + favoriteColor
            + "\n"
            + "  execution count (from job map) is "
            + count
            + "\n"
            + "  execution count (from job member variable) is "
            + _counter);

    // increment the count and store it back into the
    // job map so that job state can be properly maintained
    count++;
    data.put(EXECUTION_COUNT, count);

    // Increment the local member variable
    // This serves no real purpose since job state can not
    // be maintained via member variables!
    _counter++;
  }
 public void execute(final JobExecutionContext jobExecutionContext) throws JobExecutionException {
   try {
     if (getBlockoutManager().shouldFireNow()
         || isBlockoutAction(
             jobExecutionContext)) { // We should always let the blockouts fire //$NON-NLS-1$
       final long start = System.currentTimeMillis();
       makeAuditRecord(0, MessageTypes.INSTANCE_START, jobExecutionContext);
       createUnderlyingJob().execute(jobExecutionContext);
       final long end = System.currentTimeMillis();
       makeAuditRecord(
           ((float) (end - start) / 1000), MessageTypes.INSTANCE_END, jobExecutionContext);
     } else {
       getLogger()
           .warn(
               "Job '"
                   + jobExecutionContext.getJobDetail().getName()
                   + "' attempted to run during a blockout period.  This job was not executed");
     }
   } catch (SchedulerException e) {
     getLogger()
         .warn(
             "Got Exception retrieving the Blockout Manager for job '"
                 + jobExecutionContext.getJobDetail().getName()
                 + "'. Executing the underlying job anyway",
             e);
     createUnderlyingJob().execute(jobExecutionContext);
   }
 }
Exemplo n.º 7
0
  /**
   * Execute the job. Called by the <code>{@link org.quartz.Scheduler}</code> when a <code>
   * {@link org.quartz.Trigger}</code> fires that is associated with the <code>Job</code>.
   *
   * @throws JobExecutionException if there is an exception while executing the job.
   */
  public void execute(JobExecutionContext context) throws JobExecutionException {
    try {
      String instName = context.getJobDetail().getName();
      String instGroup = context.getJobDetail().getGroup();

      JobDataMap dataMap = context.getJobDetail().getJobDataMap();

      //	String jobSays = dataMap.getString("jobSays");
      //  float myFloatValue = dataMap.getFloat("myFloatValue");
      // test_name and hostname should extracted from context
      String application = dataMap.getString("application");
      String hostname = dataMap.getString("hostname");

      // System.err.println("Instance " + instName + " of DumbJob says: " + jobSays);
      // Call Submition API
      SmartfrogAdapter sfAdap =
          new SmartFrogAdapterImpl("D:\\cvs\\forge\\2006\\aug21\\core\\smartfrog\\dist", false);
      Map cd1 = sfAdap.submit(application, null, new String[] {hostname});

      // Say Hello to the World and display the date/time
      log.info("Hello World! - " + new Date());
      log.info("Submission Done " + cd1.toString());
    } catch (Exception ex) {
      log.error(ex);
    }
  }
Exemplo n.º 8
0
  public void execute(JobExecutionContext _context) throws JobExecutionException {

    String cacheId = (String) _context.getJobDetail().getJobDataMap().get("cacheId");
    IWriteCache c = CacheManager.getWrite2DBCache(cacheId);
    List<ArkContent> list = c.getAll();
    c.clear();

    System.out.println("job-" + _context.getJobDetail().getName() + " execute..." + list.size());

    ISession session = null;
    try {
      if (false) {

        if (list != null && list.size() > 0) {
          session = LocalContextHelper.currentSession();
          for (Iterator<ArkContent> iterator = list.iterator(); iterator.hasNext(); ) {
            session.save(iterator.next());
          }
        }
      }
    } catch (Exception e) {
      logger.error("error when write arkcontent to DB.", e);
    } finally {
      if (session != null)
        try {
          session.close();
        } catch (PureException e) {
          logger.error("error when close session.", e);
        }
      if (list != null) list.clear();
    }
  }
  /** @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));
      }
    }
  }
Exemplo n.º 10
0
 public void execute(JobExecutionContext exeInfo) throws JobExecutionException {
   System.out.println("IN execute job warning");
   System.out.println("auction ID: " + exeInfo.getJobDetail().getJobDataMap().getInt("auctionId"));
   MailSender.sendAuctionWarningMailToOwner(
       exeInfo.getJobDetail().getJobDataMap().getString("mail"),
       exeInfo.getJobDetail().getJobDataMap().getString("bookName"),
       exeInfo.getJobDetail().getJobDataMap().getString("personName"));
 }
Exemplo n.º 11
0
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();

    String receiverKey = (String) map.get(QuartzMessageReceiver.QUARTZ_RECEIVER_PROPERTY);
    if (receiverKey == null)
      throw new JobExecutionException(QuartzMessages.receiverNotInJobDataMap().getMessage());

    String connectorName = (String) map.get(QuartzMessageReceiver.QUARTZ_CONNECTOR_PROPERTY);
    if (connectorName == null)
      throw new JobExecutionException(QuartzMessages.connectorNotInJobDataMap().getMessage());

    AbstractConnector connector =
        (AbstractConnector) RegistryContext.getRegistry().lookupConnector(connectorName);
    if (connector == null)
      throw new JobExecutionException(QuartzMessages.noConnectorFound(connectorName).getMessage());

    AbstractMessageReceiver receiver =
        (AbstractMessageReceiver) connector.lookupReceiver(receiverKey);
    if (receiver == null)
      throw new JobExecutionException(
          QuartzMessages.noReceiverInConnector(receiverKey, connectorName).getMessage());

    Object payload =
        jobExecutionContext.getJobDetail().getJobDataMap().get(QuartzConnector.PROPERTY_PAYLOAD);

    try {
      if (payload == null) {
        String ref =
            jobExecutionContext
                .getJobDetail()
                .getJobDataMap()
                .getString(QuartzConnector.PROPERTY_PAYLOAD_REFERENCE);
        // for backward compatibility check the old payload Class property
        // too
        if (ref == null) {
          ref =
              jobExecutionContext
                  .getJobDetail()
                  .getJobDataMap()
                  .getString(QuartzConnector.PROPERTY_PAYLOAD_CLASS_NAME);
        }
        if (ref == null) {
          payload = NullPayload.getInstance();
        } else {
          payload = RegistryContext.getRegistry().lookupObject(ref);
        }

        if (payload == null) {
          logger.warn("There is no payload attached to this quartz job. Sending Null payload");
          payload = NullPayload.getInstance();
        }
      }
      receiver.routeMessage(new MuleMessage(receiver.getConnector().getMessageAdapter(payload)));
    } catch (Exception e) {
      receiver.handleException(e);
    }
  }
  /** @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();
    }
  }
Exemplo n.º 14
0
 @Override
 public void execute(JobExecutionContext context) throws JobExecutionException {
   Synchronizer runObject =
       (Synchronizer) context.getJobDetail().getJobDataMap().get(JobDataMapKey.RUN_OBJECT);
   try {
     String currentAppName =
         (String) context.getJobDetail().getJobDataMap().get(JobDataMapKey.RUN_MAGIC);
     /*EagleEye.startTrace(EagleEye.generateTraceId(null), "time://" + currentAppName + "/" + getName() + "Synchronizer");*/
     runObject.sync();
   } finally {
     /*EagleEye.endTrace();*/
   }
 }
Exemplo n.º 15
0
 @SuppressWarnings("unchecked")
 @Override
 public void execute(JobExecutionContext context) throws JobExecutionException {
   JobDataMap dataMap = context.getJobDetail().getJobDataMap();
   // 取得所传递的参数
   Map<String, Object> paramMap = (Map<String, Object>) dataMap.get("jobParams");
   SeqLinkedList seqParam = new SeqLinkedList();
   // 放入job参数信息
   if (null != paramMap) {
     Iterator<Entry<String, Object>> iter = paramMap.entrySet().iterator();
     while (iter.hasNext()) {
       Entry<String, Object> entry = iter.next();
       seqParam.putParam(entry.getKey(), entry.getValue());
     }
   }
   // 将所有代码流程添加到容器中
   seqParam.addExec(jobExecuteFlow);
   boolean exec = false;
   try {
     exec = seqParam.nextExec();
   } catch (Exception e) {
     e.printStackTrace();
   }
   // 释放内存
   seqParam = null;
   System.out.println(exec);
 }
Exemplo n.º 16
0
  /**
   * Called by the <code>{@link org.quartz.Scheduler}</code> when a <code>{@link org.quartz.Trigger}
   * </code> fires that is associated with the <code>Job</code>.
   *
   * @throws JobExecutionException if there is an exception while executing the job.
   */
  public void execute(JobExecutionContext context) throws JobExecutionException {

    _jobKey = context.getJobDetail().getKey();
    _log.info("---- " + _jobKey + " executing at " + new Date());

    try {
      // main job loop... see the JavaDOC for InterruptableJob for discussion...
      // do some work... in this example we are 'simulating' work by sleeping... :)

      for (int i = 0; i < 4; i++) {
        try {
          Thread.sleep(1000L);
        } catch (Exception ignore) {
          ignore.printStackTrace();
        }

        // periodically check if we've been interrupted...
        if (_interrupted) {
          _log.info("--- " + _jobKey + "  -- Interrupted... bailing out!");
          return; // could also choose to throw a JobExecutionException
          // if that made for sense based on the particular
          // job's responsibilities/behaviors
        }
      }

    } finally {
      _log.info("---- " + _jobKey + " completed at " + new Date());
    }
  }
Exemplo n.º 17
0
 @Override
 public void execute(JobExecutionContext arg0) throws JobExecutionException {
   ICreateIndexAllItem iciai1 = null;
   RCrawlerIndex rCrawlerIndex =
       (RCrawlerIndex) arg0.getJobDetail().getJobDataMap().get(QuartzManager.JUST_SCHEDULE_RETURN);
   List<RCrawlerIndex> rCrawlerIndexList;
   if (rCrawlerIndex != null) {
     rCrawlerIndexList = new ArrayList<RCrawlerIndex>();
     rCrawlerIndexList.add(rCrawlerIndex);
   } else rCrawlerIndexList = commonService.getObjs(RCrawlerIndex.class);
   for (RCrawlerIndex rdI : rCrawlerIndexList) {
     if ("0".equals(rdI.getIsError())
         && "0".equals(rdI.getIsOn())
         && (DictUtils.getDictMapByKey(DictUtils.INDEXPATH_TYPE, IndexPathType.CUSTOM.getValue()))
             .equals(
                 DictUtils.getDictMapByKey(
                     DictUtils.INDEXPATH_TYPE, rdI.getIndexCategory().getIndexPathType()))) {
       CustomCrawlerController crawlerController =
           new CustomCrawlerController(retrievalApplicationContext, rdI);
       crawlerController.indexAll();
       // 启动定时任务
       sechdule(rdI, new CrawlerIndexJob0());
     }
   }
 }
Exemplo n.º 18
0
 /*
  * (non-Javadoc)
  *
  * @see org.quartz.JobListener#jobWasExecuted(org.quartz.JobExecutionContext, org.quartz.JobExecutionException)
  */
 @Override
 public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
   String jobName = context.getJobDetail().getKey().getName();
   final BatchSchedule sch = batchSerivce.findSchById(jobName);
   final JobExecution job = (JobExecution) context.get(CapBatchConstants.K_JobExecution);
   if (sch != null && job != null) {
     if (sch.isNotify()
         && !CapString.isEmpty(sch.getNotifyStatus())
         && !CapString.isEmpty(sch.getNotifyTo())) {
       for (String status : sch.getNotifyStatus().split(",")) {
         if (CapString.trimNull(status).equals(job.getExitStatus().getExitCode())) {
           // 主旨
           String subject =
               MessageFormat.format(
                   mailSubject,
                   new Object[] {
                     sch.getSchId(), sch.getSchDesc(), job.getExitStatus().getExitCode()
                   });
           mailSender.sendEmail(sch.getNotifyTo().split(","), subject, buildText(job));
           break;
         }
       }
     }
   }
 }
Exemplo n.º 19
0
 /* (non-Javadoc)
  * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
  */
 @Override
 public void execute(final JobExecutionContext ctx) throws JobExecutionException {
   final JobDetail jobDetail = ctx.getJobDetail();
   final JobDataMap jobDataMap = jobDetail.getJobDataMap();
   final IElement element =
       (IElement) jobDataMap.get(CronConstants.KEY_DATA_ELEMENT_CONFIGURATION);
   final String name = (String) jobDataMap.get(CronConstants.KEY_DATA_NAME);
   final Collection<INotifier> globalNotifiers =
       (Collection<INotifier>) jobDataMap.get(CronConstants.KEY_DATA_NOTIFIERS);
   if (element != null) {
     LOGGER.debug("Going to analyze set [" + name + "], [" + element.getName() + "]");
     try {
       final AnalyzeResult result = element.analyze();
       if (result.hasToBeNotified()) {
         for (final INotifier notifier :
             buildNotifiersList(element.getNotifiers(), globalNotifiers)) {
           LOGGER.info("User [" + name + "], notifying [" + notifier.toString() + "]");
           notifier.execute(result);
         }
       }
     } catch (final CoreException e) {
       throw new JobExecutionException(e);
     }
   }
 }
Exemplo n.º 20
0
  /**
   * Called by the <code>{@link org.quartz.Scheduler}</code> when a <code>{@link org.quartz.Trigger}
   * </code> fires that is associated with the <code>Job</code>.
   *
   * @throws JobExecutionException if there is an exception while executing the job.
   */
  public void execute(JobExecutionContext context) throws JobExecutionException {

    // This job simply prints out its job name and the
    // date and time that it is running
    String jobName = context.getJobDetail().getFullName();
    _log.info("SimpleJob1 says: " + jobName + " executing at " + new Date());
  }
  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    Map<String, Object> dataMap = context.getJobDetail().getJobDataMap();
    AllianceTechnologyQueue at = (AllianceTechnologyQueue) dataMap.get("allianceTechnologyQueue");
    int needWealth = (Integer) dataMap.get("needWealth");
    int allianceId = (Integer) dataMap.get("allianceId");
    AllianceTechnology allianceTechnology = new AllianceTechnology();
    allianceTechnology.setAllianceId(at.getAllianceId());
    allianceTechnology.setLevel(at.getLevel());
    allianceTechnology.setTechnologyNo(at.getTechnologyNo());

    String[] str = (at.getTechnologyNo().split("_"));
    Map<String, Object> param = new HashMap<String, Object>();
    param.put("allianceId", at.getAllianceId());
    String like = str[0] + "%";
    //		StringBuffer sb = new StringBuffer();
    //		sb.append("%");
    //		sb.append(str[0]);
    //		sb.append("%");
    param.put("like", like);
    param.put("technologyNo", at.getTechnologyNo());
    param.put("level", at.getLevel());
    AllianceWelfareService allianceWelfareService =
        (AllianceWelfareService) ServiceLocator.getSpringBean("allianceWelfareService");
    AllianceService allianceService =
        (AllianceService) ServiceLocator.getSpringBean("allianceService");
    if (allianceWelfareService.getAllianceTechologyInfo(allianceId, str[0]) == null) {
      allianceWelfareService.insertAllianceTechnology(allianceTechnology); // 插入到联盟科技表
    } else {
      allianceWelfareService.updateAllianceTechnology(param); // 更新联盟科技
    }
    allianceWelfareService.deleteAllianceTechnologyQueue(
        at.getAllianceId(), at.getTechnologyNo()); // 删除联盟科技升级队列
    allianceService.updateAllianceWealth(at.getAllianceId(), -needWealth); // 更新联盟财富
  }
 private BundleDeploymentCriteria getCriteriaFromContext(JobExecutionContext context) {
   int bundleDeploymentId =
       context.getJobDetail().getJobDataMap().getInt(BUNDLE_DEPLOYMENT_ID_KEY);
   BundleDeploymentCriteria crit = new BundleDeploymentCriteria();
   crit.addFilterId(bundleDeploymentId);
   return crit;
 }
Exemplo n.º 23
0
  @Override
  public synchronized void jobToBeExecuted(JobExecutionContext jec) {
    if (processBusiness == null) {
      this.processBusiness = SpringHelper.getBean(IProcessBusiness.class);
    }

    final Job job = jec.getJobInstance();
    if (!(job instanceof ProcessJob)) return;

    // attach a listener on the process
    final ProcessJob pj = (ProcessJob) job;
    final ProcessJobDetail detail = (ProcessJobDetail) jec.getJobDetail();
    final QuartzTask quartzTask =
        (QuartzTask) detail.getJobDataMap().get(QuartzJobListener.PROPERTY_TASK);
    final String quartzTaskId = quartzTask.getId();

    final Task taskEntity = new Task();
    taskEntity.setIdentifier(UUID.randomUUID().toString());
    taskEntity.setState(TaskState.PENDING.name());
    taskEntity.setTaskParameterId(quartzTask.getTaskParameterId());
    taskEntity.setOwner(quartzTask.getUserId());
    taskEntity.setType(""); // TODO
    processBusiness.addTask(taskEntity);

    final ProcessListener listener =
        new StateListener(taskEntity.getIdentifier(), quartzTask.getTitle());
    pj.addListener(listener);
    LOGGER.log(Level.INFO, "Run task " + taskEntity.getIdentifier());
  }
Exemplo n.º 24
0
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

      String noteId = context.getJobDetail().getJobDataMap().getString("noteId");
      Note note = notebook.getNote(noteId);
      note.runAll();
    }
Exemplo n.º 25
0
  /**
   * Called by the <code>{@link org.quartz.Scheduler}</code> when a <code>{@link org.quartz.Trigger}
   * </code> fires that is associated with the <code>Job</code>.
   *
   * @throws org.quartz.JobExecutionException if there is an exception while executing the job.
   */
  public void execute(JobExecutionContext context) throws JobExecutionException {

    // This job simply prints out its job name and the
    // date and time that it is running
    JobKey jobKey = context.getJobDetail().getKey();
    _log.info("SimpleJob says: " + jobKey + "执行于 " + new Date());
  }
Exemplo n.º 26
0
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

      String noteId = context.getJobDetail().getJobDataMap().getString("noteId");
      Note note = notebook.getNote(noteId);
      note.runAll();

      while (!note.isTerminated()) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          logger.error(e.toString(), e);
        }
      }

      boolean releaseResource = false;
      try {
        Map<String, Object> config = note.getConfig();
        if (config != null && config.containsKey("releaseresource")) {
          releaseResource = (boolean) note.getConfig().get("releaseresource");
        }
      } catch (ClassCastException e) {
        logger.error(e.getMessage(), e);
      }
      if (releaseResource) {
        for (InterpreterSetting setting :
            notebook.getInterpreterFactory().getInterpreterSettings(note.getId())) {
          notebook.getInterpreterFactory().restart(setting.getId());
        }
      }
    }
  // Run this if job is about to be executed.
  @Override
  public void jobToBeExecuted(JobExecutionContext context) {

    String jobName = context.getJobDetail().getKey().toString();
    System.out.println("jobToBeExecuted");
    System.out.println("Job : " + jobName + " is going to start...");
  }
Exemplo n.º 28
0
  private void mail(JobExecutionContext jec, Set emails, String subject, String mail) {
    try {
      log.info("Sending mail to service admins: " + Arrays.toString(emails.toArray()));

      for (String email : (Set<String>) emails) {
        if (isInterrupted()) {
          log.info("Interrupted, ending monitoring job");
          return;
        }

        try {
          Mailer.sendMail(
              (String) jec.getJobDetail().getJobDataMap().get("from.name"),
              (String) jec.getJobDetail().getJobDataMap().get("from.email"),
              email,
              subject,
              mail);
        } catch (Exception e) {
          log.error("Error sending mail to service admin " + email, e);
        }
      }
    } catch (Exception e) {
      log.error("Error sending mail to service admins", e);
    }
  }
Exemplo n.º 29
0
  /** 提醒操作 */
  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 获取添加任务时的参数(时间)
    JobDataMap data = context.getJobDetail().getJobDataMap();
    Long time = data.getLong("time");
    List<Remind> reminds = new RemindService().loadByTime(time); // 数据库读取time时刻提醒
    for (int i = 0; i < reminds.size(); i++) {
      // 执行post请求微信服务器
      int id = reminds.get(i).getId();
      String response =
          Util.loadJSON("http://ly.linteng.wang/xs/home/index/send?key=wanglinteng&id=" + id);
      try {
        Util.SendLog(
            " 执行时间为:"
                + dateformat.format(new Date(time * 1000))
                + " 的定时任务,提醒ID为:【"
                + id
                + "】,返回值:"
                + response);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    Quartz.removeJob(time); // 执行完立即移除自己的触发器
  }
Exemplo n.º 30
0
 @Override
 public void execute(JobExecutionContext context) throws JobExecutionException {
   try {
     logger.info("start task....");
     String appId = String.valueOf(context.getJobDetail().getJobDataMap().get("appId"));
     String srcPath = String.valueOf(context.getJobDetail().getJobDataMap().get("srcPath"));
     String ipList = String.valueOf(context.getJobDetail().getJobDataMap().get("ipList"));
     Node node = (Node) (context.getScheduler().getContext().get("node"));
     ICommand command = new DeployCommand(appId, Node.DEPLOY, srcPath, ipList);
     node.executeCommand(command);
   } catch (SchedulerException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     logger.error("error3___" + e.getMessage(), e);
   }
 }