protected void initJobState() throws Exception {
    List<String> groupNames = _persistedScheduler.getJobGroupNames();

    for (String groupName : groupNames) {
      Set<JobKey> jobkeys = _persistedScheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName));

      for (JobKey jobKey : jobkeys) {
        Trigger trigger =
            _persistedScheduler.getTrigger(new TriggerKey(jobKey.getName(), jobKey.getGroup()));

        if (trigger != null) {
          continue;
        }

        JobDetail jobDetail = _persistedScheduler.getJobDetail(jobKey);

        JobDataMap jobDataMap = jobDetail.getJobDataMap();

        Message message = getMessage(jobDataMap);

        message.put(SchedulerEngine.JOB_NAME, jobKey.getName());
        message.put(SchedulerEngine.GROUP_NAME, jobKey.getGroup());

        if (_schedulerEngineHelper != null) {
          _schedulerEngineHelper.auditSchedulerJobs(message, TriggerState.EXPIRED);
        }

        _persistedScheduler.deleteJob(jobKey);
      }
    }
  }
Esempio n. 2
0
 public void execute(JobExecutionContext jobContext) throws JobExecutionException {
   SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
   JobKey jobKey = jobContext.getJobDetail().getKey();
   Long id = Long.parseLong(jobKey.getName());
   Event event = eventDAO.findById(id);
   MailService.sendMail(event, getRecipients(event));
   CronScheduler.removeJob(jobKey);
 }
Esempio n. 3
0
 public List<RunTimeJobDetail> listAllJobs() throws SchedulerException {
   List<RunTimeJobDetail> jobs = new ArrayList<RunTimeJobDetail>();
   for (String groupName : quartzScheduler.getJobGroupNames()) {
     for (JobKey jobKey : quartzScheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
       jobs.add(getJobDetails(groupName, jobKey.getName()));
     }
   }
   return jobs;
 }
  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;
  }
  @Test
  public void shouldCheckWhetherJobExists() throws JobPersistenceException {
    final String jobId = id("fooid");
    JobDetail job = newJob(DummyJobListener.class).withIdentity(jobId, "bargroup").build();

    assertFalse(couchdbStore.checkExists(JobKey.jobKey(jobId, "bargroup")));
    couchdbStore.storeJob(job, false);
    assertTrue(couchdbStore.checkExists(JobKey.jobKey(jobId, "bargroup")));
  }
    @Override
    public void resumeJobs(GroupMatcher<JobKey> groupMatcher) {
      String groupName = groupMatcher.getCompareToValue();

      for (JobKey jobKey : _jobs.keySet()) {
        if (jobKey.getGroup().equals(groupName)) {
          resumeJob(jobKey);
        }
      }
    }
Esempio n. 7
0
  public void scheduleJobs() throws Exception {

    System.out.println("------- Initializing ----------------------");
    checkConfiguration();

    // First we must get a reference to a scheduler
    SchedulerFactory sf = new StdSchedulerFactory();
    sched = sf.getScheduler();
    sched.deleteJob(JobKey.jobKey("event-search-job", "search.broker.jobs"));
    sched.deleteJob(JobKey.jobKey("traffic-search-job", "search.broker.jobs"));
    // sched.deleteJob(JobKey.jobKey("sport-search-job",  "search.broker.jobs"));
    // sched.deleteJob(JobKey.jobKey("data-analysis-job", "search.broker.jobs"));

    System.out.println("------- Initialization Complete -----------");
    System.out.println("------- Scheduling Jobs -------------------");

    // Job #1 is scheduled to run every 3 minutes
    JobDetail evtJob =
        newJob(EventSearchJob.class).withIdentity("event-search-job", "search.broker.jobs").build();
    Trigger ET =
        newTrigger()
            .withIdentity("event-trigger", "search.broker.jobs")
            .startNow()
            .withSchedule(simpleSchedule().withIntervalInSeconds(60 * 03).repeatForever())
            .build();

    JobDetail tfcJob =
        newJob(TrafficSearchJob.class)
            .withIdentity("traffic-search-job", "search.broker.jobs")
            .build();
    Trigger TT =
        newTrigger()
            .withIdentity("traffic-trigger", "search.broker.jobs")
            .startNow()
            .withSchedule(simpleSchedule().withIntervalInSeconds(60 * 03).repeatForever())
            .build();

    /*JobDetail danJob = newJob(DataAnalysisJob.class).withIdentity("data-analysis-job", "search.broker.jobs").build();
    Trigger DT = newTrigger().withIdentity("analysis-trigger", "search.broker.jobs")
    				  .startNow().withSchedule(simpleSchedule().withIntervalInSeconds(60*15).repeatForever())
    		          .build();

       JobDetail spoJob = newJob(SportSearchJob.class).withIdentity("sport-search-job", "search.broker.jobs").build();
    Trigger ST = newTrigger().withIdentity("sport-trigger", "search.broker.jobs")
    				  .startNow().withSchedule(simpleSchedule().withIntervalInSeconds(60*10).repeatForever())
    		          .build();*/

    sched.scheduleJob(tfcJob, TT);
    sched.scheduleJob(evtJob, ET);
    // sched.scheduleJob(spoJob, ST);
    // sched.scheduleJob(danJob, DT);

    sched.start();
    System.out.println("[eduzi] all jobs started.");
  }
Esempio n. 8
0
  @Override
  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    JobKey jobKey = context.getTrigger().getJobKey();

    XxlJobInfo jobInfo =
        DynamicSchedulerUtil.xxlJobInfoDao.load(jobKey.getGroup(), jobKey.getName());
    // save log
    XxlJobLog jobLog = new XxlJobLog();
    jobLog.setJobGroup(jobInfo.getJobGroup());
    jobLog.setJobName(jobInfo.getJobName());
    jobLog.setJobCron(jobInfo.getJobCron());
    jobLog.setJobDesc(jobInfo.getJobDesc());
    jobLog.setJobClass(jobInfo.getJobClass());
    DynamicSchedulerUtil.xxlJobLogDao.save(jobLog);
    logger.info(">>>>>>>>>>> xxl-job trigger start, jobId:{}", jobLog.getId());

    // trigger request
    HashMap<String, String> params = new HashMap<String, String>();
    params.put(HandlerParamEnum.TIMESTAMP.name(), String.valueOf(System.currentTimeMillis()));
    params.put(HandlerParamEnum.ACTION.name(), ActionEnum.RUN.name());

    params.put(
        HandlerParamEnum.LOG_ADDRESS.name(), XxlJobLogCallbackServer.getTrigger_log_address());
    params.put(HandlerParamEnum.LOG_ID.name(), String.valueOf(jobLog.getId()));

    params.put(HandlerParamEnum.EXECUTOR_HANDLER.name(), jobInfo.getExecutorHandler());
    params.put(HandlerParamEnum.EXECUTOR_PARAMS.name(), jobInfo.getExecutorParam());

    params.put(HandlerParamEnum.GLUE_SWITCH.name(), String.valueOf(jobInfo.getGlueSwitch()));
    params.put(HandlerParamEnum.JOB_GROUP.name(), jobInfo.getJobGroup());
    params.put(HandlerParamEnum.JOB_NAME.name(), jobInfo.getJobName());

    // failover trigger
    RemoteCallBack callback = failoverTrigger(jobInfo.getExecutorAddress(), params, jobLog);
    jobLog.setExecutorHandler(
        jobInfo.getGlueSwitch() == 0 ? jobInfo.getExecutorHandler() : "GLUE任务");
    jobLog.setExecutorParam(jobInfo.getExecutorParam());
    logger.info(
        ">>>>>>>>>>> xxl-job failoverTrigger response, jobId:{}, callback:{}",
        jobLog.getId(),
        callback);

    // update trigger info
    jobLog.setTriggerTime(new Date());
    jobLog.setTriggerStatus(callback.getStatus());
    jobLog.setTriggerMsg(callback.getMsg());
    DynamicSchedulerUtil.xxlJobLogDao.updateTriggerInfo(jobLog);

    // monitor triger
    JobMonitorHelper.monitor(jobLog.getId());

    logger.info(">>>>>>>>>>> xxl-job trigger end, jobId:{}", jobLog.getId());
  }
    @Override
    public List<String> getJobGroupNames() {
      List<String> groupNames = new ArrayList<>();

      for (JobKey jobKey : _jobs.keySet()) {
        if (!groupNames.contains(jobKey.getGroup())) {
          groupNames.add(jobKey.getGroup());
        }
      }

      return groupNames;
    }
  @Test
  public void shouldDeleteExistingJob() throws JobPersistenceException {
    final String jobId = id("fooid");
    JobDetail job =
        newJob(DummyJobListener.class)
            .withIdentity(jobId, "bargroup")
            .usingJobData("foo", "bar")
            .build();
    couchdbStore.storeJob(job, false);

    couchdbStore.removeJob(JobKey.jobKey(jobId, "bargroup"));
    assertNull(couchdbStore.retrieveJob(JobKey.jobKey(jobId, "bargroup")));
  }
    @Override
    public Set<JobKey> getJobKeys(GroupMatcher<JobKey> groupMatcher) {
      String groupName = groupMatcher.getCompareToValue();

      Set<JobKey> jobKeys = new HashSet<>();

      for (JobKey jobKey : _jobs.keySet()) {
        if (jobKey.getGroup().equals(groupName)) {
          jobKeys.add(jobKey);
        }
      }

      return jobKeys;
    }
 private boolean fetchJob(Connection conn, JobKey jobKey)
     throws IOException, SQLException, SchedulerException {
   PreparedStatement ps = null;
   ResultSet rs = null;
   try {
     ps = conn.prepareStatement(rtp(FETCH_JOB_DETAIL_TRACK, scheduler.getSchedulerName()));
     ps.setString(1, jobKey.getGroup());
     ps.setString(2, jobKey.getName());
     rs = ps.executeQuery();
     return rs.next();
   } finally {
     closeStatement(ps);
     cleanupConnection(conn);
   }
 }
Esempio n. 13
0
  @Async
  public void runJob(JobDetails jobDetails, Scheduler scheduler)
      throws JobExecutionAlreadyRunningException, JobRestartException,
          JobInstanceAlreadyCompleteException, JobParametersInvalidException,
          SpartanPersistenceException, SchedulerException, ClassNotFoundException {
    Map<String, JobParameter> jobMapParams = new HashMap<String, JobParameter>();
    JobParameter paramMonth = new JobParameter(1l);
    jobMapParams.put("salForMonth", paramMonth);

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

    JobParameters defaultParams = new JobParameters(jobMapParams);

    JobDataMap newJobData = new JobDataMap(jobMapParams);

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

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

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

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

          } else {
            schdeuleJob(jobClass, scheduler, jobDetails, newJobData);
          }
        }
      }
    }
  }
  @Test
  public void shouldStoreAndRetrieveJob() throws JobPersistenceException {
    final String jobId = id("fooid");
    JobDetail job =
        newJob(DummyJobListener.class)
            .withIdentity(jobId, "bargroup")
            .usingJobData("foo", "bar")
            .usingJobData("fuu", "baz")
            .build();
    couchdbStore.storeJob(job, false);

    assertNull(couchdbStore.retrieveJob(JobKey.jobKey("something", "something")));
    assertEquals(
        "bar",
        couchdbStore.retrieveJob(JobKey.jobKey(jobId, "bargroup")).getJobDataMap().get("foo"));
  }
  @Test
  public void shouldReturnMatchingJobKeys() throws JobPersistenceException {
    JobDetail job1 = newJob(DummyJobListener.class).withIdentity(id("fooid1"), "bargroup1").build();
    final String groupId = id("bargroup2");
    final String job1Id = id("fooid2");
    final String job2Id = id("fooid3");
    JobDetail job2 = newJob(DummyJobListener.class).withIdentity(job1Id, groupId).build();
    JobDetail job3 = newJob(DummyJobListener.class).withIdentity(job2Id, groupId).build();
    couchdbStore.storeJob(job1, false);
    couchdbStore.storeJob(job2, false);
    couchdbStore.storeJob(job3, false);

    assertEquals(
        new HashSet<JobKey>(asList(JobKey.jobKey(job1Id, groupId), JobKey.jobKey(job2Id, groupId))),
        couchdbStore.getJobKeys(GroupMatcher.<JobKey>groupEquals(groupId)));
  }
Esempio n. 16
0
  public List<RunTimeJobDetail> searchJobs(String groupExp, String nameExp)
      throws SchedulerException {
    Pattern groupPattern = Pattern.compile(groupExp);
    Pattern namePattern = Pattern.compile(nameExp);

    List<RunTimeJobDetail> jobs = new ArrayList<RunTimeJobDetail>();
    for (String groupName : quartzScheduler.getJobGroupNames()) {
      if (groupPattern.matcher(groupName).matches()) {
        for (JobKey jobKey : quartzScheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
          if (namePattern.matcher(jobKey.getName()).matches()) {
            jobs.add(getJobDetails(groupName, jobKey.getName()));
          }
        }
      }
    }
    return jobs;
  }
 private Object getJobExecParams(Connection conn, JobKey jobKey, String restart)
     throws IOException, SQLException, SchedulerException, ClassNotFoundException {
   PreparedStatement ps = null;
   ResultSet rs = null;
   try {
     ps = conn.prepareStatement(rtp(FETCH_JOB_DETAIL_EXEC_TRACK, scheduler.getSchedulerName()));
     ps.setString(1, jobKey.getGroup());
     ps.setString(2, jobKey.getName());
     ps.setString(3, restart);
     rs = ps.executeQuery();
     rs.next();
     return getJobDataFromBlob(rs, "JOB_DATA");
   } finally {
     closeStatement(ps);
     cleanupConnection(conn);
   }
 }
Esempio n. 18
0
 /**
  * Delete all {@link Job}s of the group <code>persistModelName</code>
  *
  * @throws SchedulerException if there is an internal Scheduler error.
  */
 private void removeTimers(String persistModelName) {
   try {
     Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(persistModelName));
     for (JobKey jobKey : jobKeys) {
       try {
         boolean success = scheduler.deleteJob(jobKey);
         if (success) {
           logger.debug("Removed scheduled cron job for strategy '{}'", jobKey.toString());
         } else {
           logger.warn("Failed to delete cron jobs '{}'", jobKey.getName());
         }
       } catch (SchedulerException e) {
         logger.warn("Failed to delete cron jobs '{}'", jobKey.getName());
       }
     }
   } catch (SchedulerException e) {
     logger.warn("Failed to delete cron jobs of group '{}'", persistModelName);
   }
 }
  @Test
  public void shouldDeleteExistingJobs() throws JobPersistenceException {
    final String job1Id = id("fooid1");
    JobDetail job1 = newJob(DummyJobListener.class).withIdentity(job1Id, "bargroup1").build();
    final String job2Id = id("fooid2");
    JobDetail job2 = newJob(DummyJobListener.class).withIdentity(job2Id, "bargroup2").build();
    final String job3Id = id("fooid3");
    JobDetail job3 = newJob(DummyJobListener.class).withIdentity(job3Id, "bargroup2").build();

    couchdbStore.storeJob(job1, false);
    couchdbStore.storeJob(job2, false);
    couchdbStore.storeJob(job3, false);

    couchdbStore.removeJobs(
        asList(JobKey.jobKey(job1Id, "bargroup1"), JobKey.jobKey(job2Id, "bargroup2")));

    assertNull(couchdbStore.retrieveJob(JobKey.jobKey(job1Id, "bargroup1")));
    assertNull(couchdbStore.retrieveJob(JobKey.jobKey(job2Id, "bargroup2")));
    assertNotNull(couchdbStore.retrieveJob(JobKey.jobKey(job3Id, "bargroup2")));
  }
  @Test
  public void shouldDeleteAssociatedTriggersWhenDeletingJob() throws JobPersistenceException {
    final String jobId = id("job");
    JobDetail job = newJob(DummyJobListener.class).withIdentity(jobId, "bargroup").build();
    couchdbStore.storeJob(job, false);

    final String tridderName = id("trigger");
    SimpleTriggerImpl trigger =
        (SimpleTriggerImpl)
            newTrigger()
                .withIdentity(tridderName, "borgroup")
                .forJob(JobKey.jobKey(jobId, "bargroup"))
                .startAt(new Date(2010, 10, 20))
                .withSchedule(simpleSchedule().withIntervalInMinutes(2).repeatForever())
                .build();
    couchdbStore.storeTrigger(trigger, false);

    couchdbStore.removeJob(JobKey.jobKey(jobId, "bargroup"));
    assertNull(couchdbStore.retrieveTrigger(TriggerKey.triggerKey(tridderName, "borgroup")));
  }
  public void stop(Long id) throws Exception {
    synchronized (sync) {
      String jobKey = scheduledJobKeys.remove(id);
      if (jobKey == null) {
        throw new IllegalArgumentException("No scheduled job for function id " + id);
      }

      quartzScheduler.deleteJob(JobKey.jobKey(jobKey));

      LOG.info("Stopped {}", jobKey);
    }
  }
  protected void unschedule(Scheduler scheduler, JobKey jobKey) throws Exception {

    JobDetail jobDetail = scheduler.getJobDetail(jobKey);

    TriggerKey triggerKey = new TriggerKey(jobKey.getName(), jobKey.getGroup());

    if (jobDetail == null) {
      return;
    }

    unregisterMessageListener(scheduler, jobKey);

    JobDataMap jobDataMap = jobDetail.getJobDataMap();

    JobState jobState = getJobState(jobDataMap);

    Trigger trigger = scheduler.getTrigger(triggerKey);

    if (trigger == null) {
      return;
    }

    jobState.setTriggerDate(SchedulerEngine.END_TIME, new Date());
    jobState.setTriggerDate(SchedulerEngine.FINAL_FIRE_TIME, trigger.getPreviousFireTime());
    jobState.setTriggerDate(SchedulerEngine.NEXT_FIRE_TIME, null);
    jobState.setTriggerDate(SchedulerEngine.PREVIOUS_FIRE_TIME, trigger.getPreviousFireTime());
    jobState.setTriggerDate(SchedulerEngine.START_TIME, trigger.getStartTime());

    jobState.setTriggerState(TriggerState.UNSCHEDULED);

    jobState.clearExceptions();

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

    scheduler.unscheduleJob(triggerKey);

    scheduler.addJob(jobDetail, true);
  }
Esempio n. 23
0
  /**
   * Creates and schedules a new quartz-job and trigger with model and rule name as jobData.
   *
   * @param rule the rule to schedule
   * @param trigger the defined trigger
   * @throws SchedulerException if there is an internal Scheduler error.
   */
  private void createTimers(String modelName) {
    PersistenceModel persistModel =
        (PersistenceModel) modelRepository.getModel(modelName + ".persist");
    if (persistModel != null) {
      for (Strategy strategy : persistModel.getStrategies()) {
        if (strategy instanceof CronStrategy) {
          CronStrategy cronStrategy = (CronStrategy) strategy;
          String cronExpression = cronStrategy.getCronExpression();
          JobKey jobKey = new JobKey(strategy.getName(), modelName);
          try {
            JobDetail job =
                newJob(PersistItemsJob.class)
                    .usingJobData(
                        PersistItemsJob.JOB_DATA_PERSISTMODEL,
                        cronStrategy.eResource().getURI().trimFileExtension().path())
                    .usingJobData(PersistItemsJob.JOB_DATA_STRATEGYNAME, cronStrategy.getName())
                    .withIdentity(jobKey)
                    .build();

            Trigger quartzTrigger =
                newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();

            scheduler.scheduleJob(job, quartzTrigger);

            logger.debug(
                "Scheduled strategy {} with cron expression {}",
                new Object[] {jobKey.toString(), cronExpression});
          } catch (SchedulerException e) {
            logger.error(
                "Failed to schedule job for strategy {} with cron expression {}",
                new String[] {jobKey.toString(), cronExpression},
                e);
          }
        }
      }
    }
  }
  @Test
  public void shouldReturnAllJobs() throws JobPersistenceException {
    String group1Id = id("group1Id");
    String group2Id = id("group2Id");
    String jobid1 = id("fooid1");
    String jobid2 = id("fooid2");
    String jobid3 = id("fooid3");
    JobDetail job1 = newJob(DummyJobListener.class).withIdentity(jobid1, group1Id).build();
    JobDetail job2 = newJob(DummyJobListener.class).withIdentity(jobid2, group2Id).build();
    JobDetail job3 = newJob(DummyJobListener.class).withIdentity(jobid3, group2Id).build();
    couchdbStore.storeJob(job1, false);
    couchdbStore.storeJob(job2, false);
    couchdbStore.storeJob(job3, false);

    List<CouchDbJobDetail> jobs =
        couchdbStore
            .getJobStore()
            .getJobs(asList(JobKey.jobKey(jobid1, group1Id), JobKey.jobKey(jobid3, group2Id)));
    List<JobKey> jobKeys = extract(jobs, on(CouchDbJobDetail.class).getKey());

    assertEquals(2, jobs.size());
    assertTrue(jobKeys.contains(JobKey.jobKey(jobid1, group1Id)));
    assertTrue(jobKeys.contains(JobKey.jobKey(jobid3, group2Id)));
  }
  @Test(expected = ObjectAlreadyExistsException.class)
  public void shouldNotUpdateExistingJob() throws JobPersistenceException {
    JobDetail job =
        newJob(DummyJobListener.class)
            .withIdentity("fooid", "bargroup")
            .usingJobData("foo", "bar")
            .build();
    couchdbStore.storeJob(job, false);

    JobDetail newJob =
        newJob(DummyJobListener.class)
            .withIdentity("fooid", "bargroup")
            .usingJobData("fii", "bur")
            .build();
    couchdbStore.storeJob(newJob, false);

    assertNull(
        couchdbStore.retrieveJob(JobKey.jobKey("fooid", "bargroup")).getJobDataMap().get("fii"));
  }
  @Test
  public void shouldUpdateExistingJob() throws JobPersistenceException {
    final String jobId = id("fooid");
    JobDetail job =
        newJob(DummyJobListener.class)
            .withIdentity(jobId, "bargroup")
            .usingJobData("foo", "bar")
            .build();
    couchdbStore.storeJob(job, false);

    JobDetail newJob =
        newJob(DummyJobListener.class)
            .withIdentity(jobId, "bargroup")
            .usingJobData("fii", "bur")
            .build();
    couchdbStore.storeJob(newJob, true);

    assertEquals(
        "bur",
        couchdbStore.retrieveJob(JobKey.jobKey(jobId, "bargroup")).getJobDataMap().get("fii"));
  }
Esempio n. 27
0
 @Override
 public void execute(JobExecutionContext context) throws JobExecutionException {
   JobKey key = context.getJobDetail().getKey();
   logger.info("-----job key---" + key.getName());
   logger.info("----hello--" + new Date());
 }
  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());

    if (trigger instanceof CalendarIntervalTrigger) {
      CalendarIntervalTrigger calendarIntervalTrigger = CalendarIntervalTrigger.class.cast(trigger);

      IntervalUnit intervalUnit = calendarIntervalTrigger.getRepeatIntervalUnit();

      schedulerResponse.setTrigger(
          new IntervalTrigger(
              jobName,
              groupName,
              calendarIntervalTrigger.getStartTime(),
              calendarIntervalTrigger.getEndTime(),
              calendarIntervalTrigger.getRepeatInterval(),
              TimeUnit.valueOf(intervalUnit.name())));
    } else if (trigger instanceof CronTrigger) {
      CronTrigger cronTrigger = CronTrigger.class.cast(trigger);

      schedulerResponse.setTrigger(
          new com.liferay.portal.kernel.scheduler.CronTrigger(
              jobName,
              groupName,
              cronTrigger.getStartTime(),
              cronTrigger.getEndTime(),
              cronTrigger.getCronExpression()));
    } else if (trigger instanceof SimpleTrigger) {
      SimpleTrigger simpleTrigger = SimpleTrigger.class.cast(trigger);

      schedulerResponse.setTrigger(
          new IntervalTrigger(
              jobName,
              groupName,
              simpleTrigger.getStartTime(),
              simpleTrigger.getEndTime(),
              (int) simpleTrigger.getRepeatInterval(),
              TimeUnit.MILLISECOND));
    }

    return schedulerResponse;
  }
Esempio n. 29
0
 private String getJobKeyAsString(final JobKey jobKey) {
   return jobKey.getName() + SchedulerServiceConstants.JOB_KEY_SEPERATOR + jobKey.getGroup();
 }