protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
   try {
     SchedulerContext schCtx = context.getScheduler().getContext();
     // 获取Spring中的上下文
     ApplicationContext appCtx = (ApplicationContext) schCtx.get("applicationContext");
     this.staticPageSvc = (StaticPageSvc) appCtx.getBean("staticPageSvc");
     JobDataMap jdm = context.getJobDetail().getJobDataMap();
     // 获取栏目
     String channelIdStr = (String) jdm.get(CmsTask.TASK_PARAM_CHANNEL_ID);
     if (!StringUtils.isBlank(channelIdStr)) {
       this.channelId = Integer.parseInt(channelIdStr);
       if (channelId.equals(0)) {
         channelId = null;
       }
     }
     // 获取站点
     String siteIdStr = (String) jdm.get(CmsTask.TASK_PARAM_SITE_ID);
     if (!StringUtils.isBlank(siteIdStr)) {
       this.siteId = Integer.parseInt(siteIdStr);
     }
   } catch (SchedulerException e1) {
     // TODO 尚未处理异常
     e1.printStackTrace();
   }
   staitcChannel();
 }
  private int insertJobDetail(Connection conn, JobExecutionContext context)
      throws IOException, SQLException, SchedulerException {

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

    Object oResult = context.getResult();

    ByteArrayOutputStream baos = serializeJobData(jobDataMap);

    ByteArrayOutputStream baosResult = serializeObject(oResult);

    PreparedStatement ps = null;

    int insertResult = 0;

    try {
      ps = conn.prepareStatement(rtp(INSERT_JOB_DETAIL_TRACK, scheduler.getSchedulerName()));
      ps.setString(1, job.getKey().getName());
      ps.setString(2, job.getKey().getGroup());

      String instanceId = context.getFireInstanceId();
      ps.setString(3, instanceId);

      ps.setString(4, job.getDescription());
      ps.setString(5, job.getJobClass().getName());
      // TODO verify it works with DB2v8
      // DB2v8 : ps.setInt(6, ((job.isDurable()) ? 1 : 0));
      ps.setBoolean(6, job.isDurable());
      // TODO verify it works with DB2v8
      // DB2v8 : ps.setInt(7, ((job.isConcurrentExectionDisallowed()) ? 1 : 0));
      ps.setBoolean(7, job.isConcurrentExectionDisallowed());
      // TODO verify it works with DB2v8
      // DB2v8 : ps.setInt(8, ((job.isPersistJobDataAfterExecution()) ? 1 : 0));
      ps.setBoolean(8, job.isPersistJobDataAfterExecution());
      // TODO verify it works with DB2v8
      // DB2v8 : ps.setInt(9, ((job.requestsRecovery()) ? 1 : 0));
      ps.setBoolean(9, job.requestsRecovery());
      // TODO verify it works with Sybase
      // Sybase : ps.setBytes(10, (baos == null) ? null: baos.toByteArray());
      ps.setBytes(10, (baos == null) ? new byte[0] : baos.toByteArray());
      ps.setBytes(11, (baosResult == null) ? new byte[0] : baosResult.toByteArray());
      String restartedInstanceId = jobDataMap.getString(RESTARTED_FIRE_INSTANCE_ID);
      ps.setString(12, restartedInstanceId);

      String returnCode = null;
      if (oResult instanceof JobDataMap) {
        returnCode = ((JobDataMap) oResult).getString(QuartzContextAdapter.RETURN_CODE);
      } else {
        returnCode = String.valueOf(oResult);
      }
      ps.setString(13, returnCode);

      insertResult = ps.executeUpdate();
    } finally {
      closeStatement(ps);
      cleanupConnection(conn);
    }
    return insertResult;
  }
Exemple #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);
    }
  }
Exemple #4
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); // 执行完立即移除自己的触发器
  }
Exemple #5
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);
     }
   }
 }
    public final void addJob(
        String jobName, String groupName, StorageType storageType, org.quartz.Trigger trigger) {

      JobKey jobKey = new JobKey(jobName, groupName);

      JobBuilder jobBuilder = JobBuilder.newJob(MessageSenderJob.class);

      jobBuilder = jobBuilder.withIdentity(jobKey);

      JobDetail jobDetail = jobBuilder.build();

      JobDataMap jobDataMap = jobDetail.getJobDataMap();

      jobDataMap.put(SchedulerEngine.MESSAGE, _jsonFactory.serialize(new Message()));
      jobDataMap.put(SchedulerEngine.DESTINATION_NAME, _TEST_DESTINATION_NAME);
      jobDataMap.put(SchedulerEngine.STORAGE_TYPE, storageType.toString());

      JobState jobState = new JobState(TriggerState.NORMAL);

      jobState.addException(new Exception(), new Date());

      jobDataMap.put(SchedulerEngine.JOB_STATE, JobStateSerializeUtil.serialize(jobState));

      _jobs.put(jobKey, new Tuple(jobDetail, trigger, TriggerState.NORMAL));
    }
  public void run() throws Exception {

    Log log = LogFactory.getLog(RemoteClientExample.class);

    // First we must get a reference to a scheduler
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler sched = sf.getScheduler();

    // define the job and ask it to run
    JobDetail job = new JobDetail("remotelyAddedJob", "default", SimpleJob.class);
    JobDataMap map = new JobDataMap();
    map.put("msg", "Your remotely added job has executed!");
    job.setJobDataMap(map);
    CronTrigger trigger =
        new CronTrigger(
            "remotelyAddedTrigger",
            "default",
            "remotelyAddedJob",
            "default",
            new Date(),
            null,
            "/5 * * ? * *");

    // schedule the job
    sched.scheduleJob(job, trigger);

    log.info("Remote job scheduled.");
  }
 @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);
 }
  public void testCreation() throws Exception {
    Scheduler scheduler = (Scheduler) lookup(Scheduler.ROLE, "test");

    assertNotNull(scheduler);

    JobDataMap dataMap = new JobDataMap();

    dataMap.put("project", "continuum");

    JobDetail jobDetail = new JobDetail("job", "group", JobOne.class);

    jobDetail.setJobDataMap(dataMap);

    Trigger trigger = new SimpleTrigger("trigger", "group");

    scheduler.addGlobalTriggerListener(this);

    scheduler.scheduleJob(jobDetail, trigger);

    while (!triggerFired) {
      // System.out.println("! triggerFired");
      Thread.sleep(10);
    }
    System.out.println("ok triggerFired");
  }
Exemple #10
0
 @Test
 public void doTest() throws SchedulerException, MeasurementException {
   PollJob job = new PollJob();
   JobExecutionContext context = mock(JobExecutionContext.class);
   Map params = new HashMap();
   JobDataMap jobMap = new JobDataMap(params);
   MeasurementDefinition def = MocksFactory.createMockMeasurementDefinition();
   MeasurementListener listener = mock(MeasurementListener.class);
   Scheduler scheduler = mock(Scheduler.class);
   CoreMeasurementService service = mock(CoreMeasurementService.class);
   SchedulerContext schedulerContext =
       new SchedulerContext(
           Collections.singletonMap(PollJob.MEASUREMENT_SERVICE_ATTR_NAME, service));
   jobMap.put(PollJob.LISTENER_ATTR_NAME, listener);
   jobMap.put(PollJob.MEASUREMENT_DEF_ATTR_NAME, def);
   jobMap.put(PollJob.MEASUREMENT_SERVICE_ATTR_NAME, service);
   when(context.getMergedJobDataMap()).thenReturn(jobMap);
   when(context.getScheduler()).thenReturn(scheduler);
   when(scheduler.getContext()).thenReturn(schedulerContext);
   CapabilityValue capValue = new CapabilityValue(RandomUtils.nextLong());
   when(service.getCapabilityValue(Matchers.<String>any(), Matchers.<String>any()))
       .thenReturn(capValue);
   job.execute(context);
   verify(context).getMergedJobDataMap();
   verify(service).getCapabilityValue(def.getResourceUri(), def.getCapabilityUri());
   verify(listener).newCapabilityValue(capValue);
   assertEquals(capValue.getMetricsId(), def.getId());
 }
  public void executeJob(final ScheduledJobDetail scheduledJobDetail, String triggerType) {
    try {
      final JobDataMap jobDataMap = new JobDataMap();
      if (triggerType == null) {
        triggerType = SchedulerServiceConstants.TRIGGER_TYPE_APPLICATION;
      }
      jobDataMap.put(SchedulerServiceConstants.TRIGGER_TYPE_REFERENCE, triggerType);
      jobDataMap.put(
          SchedulerServiceConstants.TENANT_IDENTIFIER,
          ThreadLocalContextUtil.getTenant().getTenantIdentifier());
      final String key = scheduledJobDetail.getJobKey();
      final JobKey jobKey = constructJobKey(key);
      final String schedulerName = getSchedulerName(scheduledJobDetail);
      final Scheduler scheduler = this.schedulers.get(schedulerName);
      if (scheduler == null || !scheduler.checkExists(jobKey)) {
        final JobDetail jobDetail = createJobDetail(scheduledJobDetail);
        final String tempSchedulerName = "temp" + scheduledJobDetail.getId();
        final Scheduler tempScheduler =
            createScheduler(tempSchedulerName, 1, schedulerJobListener, schedulerStopListener);
        tempScheduler.addJob(jobDetail, true);
        jobDataMap.put(SchedulerServiceConstants.SCHEDULER_NAME, tempSchedulerName);
        this.schedulers.put(tempSchedulerName, tempScheduler);
        tempScheduler.triggerJob(jobDetail.getKey(), jobDataMap);
      } else {
        scheduler.triggerJob(jobKey, jobDataMap);
      }

    } catch (final Exception e) {
      final String msg = "Job execution failed for job with id:" + scheduledJobDetail.getId();
      logger.error(msg, e);
      throw new PlatformInternalServerException(
          "error.msg.sheduler.job.execution.failed", msg, scheduledJobDetail.getId());
    }
  }
  /**
   * 新增任务
   *
   * @param locale
   * @param model
   * @return
   */
  @RequestMapping(
      value = "/addJob",
      method = {RequestMethod.POST, RequestMethod.GET})
  @ResponseBody
  public Map<String, Object> addJob(
      @RequestParam("jobName") String jobName,
      @RequestParam("type") String type,
      @RequestParam("startTime") String startTime,
      HttpServletRequest req) {
    Map<String, Object> m = new HashMap<String, Object>();
    JobDataMap jobData = new JobDataMap();
    String key = null;
    String[] value = null;
    for (Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
      key = entry.getKey();
      value = entry.getValue();
      if (value != null && value.length > 0) {
        jobData.put(key, value[0]);
      }
    }
    JobType jt = null;
    if (GloabConstant.JOB_TYPE_0.equals(type)) {
      jt = JobType.CONSULT;
    } else {
      jt = JobType.ACTIVITY;
    }
    JobManager.addJob(jobName, jt, new Date(Long.valueOf(startTime)), jobData);

    m.put("success", true);
    return m;
  }
Exemple #13
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++;
  }
Exemple #14
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);
    }
  }
  protected void updateJobState(
      Scheduler scheduler, JobKey jobKey, TriggerState triggerState, boolean suppressError)
      throws Exception {

    JobDetail jobDetail = scheduler.getJobDetail(jobKey);

    if (jobDetail == null) {
      return;
    }

    JobDataMap jobDataMap = jobDetail.getJobDataMap();

    JobState jobState = getJobState(jobDataMap);

    if (triggerState != null) {
      jobState.setTriggerState(triggerState);
    }

    if (suppressError) {
      jobState.clearExceptions();
    }

    jobDataMap.put(SchedulerEngine.JOB_STATE, JobStateSerializeUtil.serialize(jobState));

    scheduler.addJob(jobDetail, true);
  }
  private void scheduleCronJob(String cronString, String elementId) {
    try {
      SchedulerFactory schedulerFactory = new StdSchedulerFactory();
      scheduler = schedulerFactory.getScheduler();
      scheduler.start();

      JobDataMap dataMap = new JobDataMap();
      dataMap.put("trigger", this);

      jobName = "TriggerJob_" + elementId;
      JobDetail job =
          org.quartz.JobBuilder.newJob(CronEventTrigger.class)
              .withIdentity(jobName, jobGroup)
              .usingJobData(dataMap)
              .build();

      Trigger trigger =
          org.quartz.TriggerBuilder.newTrigger()
              .withIdentity("TriggerJob_" + elementId, jobGroup)
              .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
              .build();

      scheduler.scheduleJob(job, trigger);

    } catch (SchedulerException e) {
      log.error(
          "Error while instantiating quartz scheduler for trigger '"
              + triggerDefinition.getId()
              + "',"
              + e.getMessage(),
          e);
    }
  }
  /**
   * schedule a job
   *
   * @param aScheduler scheduler to start
   * @throws SchedulerException
   */
  public static void schedule(am.projects.webserver.report.vo.Scheduler aScheduler)
      throws SchedulerException {

    if (null == scheduler) return;

    JobDataMap dataMap = new JobDataMap();
    dataMap.put(am.projects.webserver.report.vo.Scheduler.class.getSimpleName(), aScheduler);

    // define the job and tie it to our HelloJob class
    String jobName = buildJobName(aScheduler);
    String groupName = buildJobGroupName(aScheduler);
    JobKey jobKey = new JobKey(jobName, groupName);

    JobDetail job = newJob(MonitorJob.class).withIdentity(jobKey).usingJobData(dataMap).build();

    TriggerKey triggerKey = new TriggerKey(jobName, groupName);
    Trigger trigger =
        newTrigger()
            .withIdentity(triggerKey)
            .startNow()
            .withSchedule(
                simpleSchedule()
                    .withIntervalInMinutes(aScheduler.getRequestRepeatIntervalInMinutes())
                    .repeatForever())
            .build();

    scheduler.scheduleJob(job, trigger);
  }
Exemple #18
0
 private long getCustomerId(SchedulingContext ctxt, Trigger t) throws JobPersistenceException {
   JobDetail jd = retrieveJob(ctxt, t.getJobName(), t.getJobGroup());
   if (jd == null) {
     return -1L;
   }
   JobDataMap jdMap = jd.getJobDataMap();
   return jdMap.getLong("customerId");
 }
  protected void unregisterMessageListener(Scheduler scheduler, JobKey jobKey) throws Exception {

    JobDetail jobDetail = scheduler.getJobDetail(jobKey);

    if (jobDetail == null) {
      return;
    }

    JobDataMap jobDataMap = jobDetail.getJobDataMap();

    if (jobDataMap == null) {
      return;
    }

    Message message = getMessage(jobDataMap);

    String messageListenerUUID = message.getString(SchedulerEngine.MESSAGE_LISTENER_UUID);

    if (messageListenerUUID == null) {
      return;
    }

    String destinationName = jobDataMap.getString(SchedulerEngine.DESTINATION_NAME);

    Destination destination = _messageBus.getDestination(destinationName);

    if (destination == null) {
      return;
    }

    Set<MessageListener> messageListeners = destination.getMessageListeners();

    for (MessageListener messageListener : messageListeners) {
      if (!(messageListener instanceof InvokerMessageListener)) {
        continue;
      }

      InvokerMessageListener invokerMessageListener = (InvokerMessageListener) messageListener;

      messageListener = invokerMessageListener.getMessageListener();

      if (!(messageListener instanceof SchedulerEventMessageListenerWrapper)) {

        continue;
      }

      SchedulerEventMessageListenerWrapper schedulerMessageListener =
          (SchedulerEventMessageListenerWrapper) messageListener;

      if (messageListenerUUID.equals(schedulerMessageListener.getMessageListenerUUID())) {

        _messageBus.unregisterMessageListener(destinationName, schedulerMessageListener);

        return;
      }
    }
  }
Exemple #20
0
 private Command<?> getCommand(JobExecutionContext context) throws JobExecutionException {
   JobDataMap dataMap = context.getJobDetail().getJobDataMap();
   String commandLine = dataMap.getString("command");
   try {
     return toCommand(commandLine);
   } catch (ArgumentValidationException ex) {
     throw new JobExecutionException("Invalid task parameter 'command': " + commandLine, ex);
   }
 }
  protected SchedulerResponse getScheduledJob(Scheduler scheduler, JobKey jobKey) throws Exception {

    JobDetail jobDetail = scheduler.getJobDetail(jobKey);

    if (jobDetail == null) {
      return null;
    }

    SchedulerResponse schedulerResponse = new SchedulerResponse();

    JobDataMap jobDataMap = jobDetail.getJobDataMap();

    String description = jobDataMap.getString(SchedulerEngine.DESCRIPTION);

    schedulerResponse.setDescription(description);

    String destinationName = jobDataMap.getString(SchedulerEngine.DESTINATION_NAME);

    schedulerResponse.setDestinationName(destinationName);

    Message message = getMessage(jobDataMap);

    JobState jobState = getJobState(jobDataMap);

    message.put(SchedulerEngine.JOB_STATE, jobState);

    schedulerResponse.setMessage(message);

    StorageType storageType =
        StorageType.valueOf(jobDataMap.getString(SchedulerEngine.STORAGE_TYPE));

    schedulerResponse.setStorageType(storageType);

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

    TriggerKey triggerKey = new TriggerKey(jobName, groupName);

    Trigger trigger = scheduler.getTrigger(triggerKey);

    if (trigger == null) {
      schedulerResponse.setGroupName(groupName);
      schedulerResponse.setJobName(jobName);

      return schedulerResponse;
    }

    message.put(SchedulerEngine.END_TIME, trigger.getEndTime());
    message.put(SchedulerEngine.FINAL_FIRE_TIME, trigger.getFinalFireTime());
    message.put(SchedulerEngine.NEXT_FIRE_TIME, trigger.getNextFireTime());
    message.put(SchedulerEngine.PREVIOUS_FIRE_TIME, trigger.getPreviousFireTime());
    message.put(SchedulerEngine.START_TIME, trigger.getStartTime());

    schedulerResponse.setTrigger(new QuartzTrigger(trigger));

    return schedulerResponse;
  }
Exemple #22
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);
    }
  }
 /**
  * 创建任务JOb
  *
  * @return
  */
 private JobDetail createJobDetail() {
   JobDataMap jobDataMap = new JobDataMap();
   jobDataMap.put("jobConfiguration", jobConfiguration);
   JobDetail result =
       JobBuilder.newJob(jobConfiguration.getJobClass())
           .setJobData(jobDataMap)
           .withIdentity(jobConfiguration.getJobName())
           .build();
   return result;
 }
  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

    JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
    CronEventTrigger cronEventTrigger = (CronEventTrigger) dataMap.get("trigger");
    if (log.isDebugEnabled()) {
      log.debug("Running Trigger Job '" + cronEventTrigger.getId() + "'");
    }
    cronEventTrigger.sendEvent();
  }
 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$
   }
 }
  /** @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));
    }
  }
 /** Calls the feed cleaner to do its work */
 public void execute(JobExecutionContext context) throws JobExecutionException {
   JobDataMap jobData = context.getJobDetail().getJobDataMap();
   // extract the feed cleaner to use
   Object feedCleanerObj = jobData.get("feedCleaner");
   if (feedCleanerObj == null || !(feedCleanerObj instanceof FeedCleaner)) {
     throw new AlfrescoRuntimeException(
         "FeedCleanupJob data must contain valid 'feedCleaner' reference");
   }
   FeedCleaner feedCleaner = (FeedCleaner) feedCleanerObj;
   feedCleaner.execute();
 }
  public static Map<String, String> convertParametersFromNativeObject(
      org.quartz.JobDataMap quartzParameters) {
    Map<String, String> spagobiParameters = new HashMap<String, String>();

    Set<String> parameterNames = quartzParameters.keySet();
    for (String parameterName : parameterNames) {
      String parameterValue = (String) quartzParameters.get(parameterName);
      spagobiParameters.put(parameterName, parameterValue);
    }
    return spagobiParameters;
  }
 JobDataMap createJobDataMap(String parameters) {
   JobDataMap map = new JobDataMap();
   if (!StringUtils.isNullOrEmpty(parameters)) {
     JSONArray jsonArray = JSON.parseArray(parameters);
     for (int i = 0; i < jsonArray.size(); i++) {
       JSONObject o = jsonArray.getJSONObject(i);
       map.put(o.getString("key"), o.get("value"));
     }
   }
   return map;
 }
 public void execute(JobExecutionContext context) throws JobExecutionException {
   JobDataMap jobData = context.getJobDetail().getJobDataMap();
   // extract the content cleaner to use
   Object certificateAlertObj = jobData.get("certificateAlert");
   if (certificateAlertObj == null || !(certificateAlertObj instanceof CertificateAlert)) {
     throw new AlfrescoRuntimeException(
         "CertificateAlertJob data must contain valid 'certificateAlert' reference");
   }
   CertificateAlert certificateAlert = (CertificateAlert) certificateAlertObj;
   certificateAlert.execute();
 }