@Test(expected = MotechSchedulerException.class)
  public void shouldNotResumeJobIfItIsNotUiDefined() throws Exception {
    try {
      Map<String, Object> params = new HashMap<>();
      params.put(MotechSchedulerService.JOB_ID_KEY, "job_id");

      JobBasicInfo info =
          new JobBasicInfo(
              JobBasicInfo.ACTIVITY_ACTIVE,
              JobBasicInfo.STATUS_PAUSED,
              "test_event-job_id",
              "default",
              "start-time",
              "nex-fire-time",
              "end-time",
              JobBasicInfo.JOBTYPE_CRON,
              "test-info",
              false);

      schedulerService.scheduleJob(
          new CronSchedulableJob(new MotechEvent("test_event", params), "0 0 12 * * ?"));
      scheduler.pauseJob(new JobKey(info.getName(), info.getGroup()));

      assertEquals(PAUSED, scheduler.getTriggerState(triggerKey("test_event-job_id", "default")));

      schedulerService.resumeJob(info);
    } finally {
      assertEquals(PAUSED, scheduler.getTriggerState(triggerKey("test_event-job_id", "default")));
    }
  }
 /** pauses a job with the given jobId assuming the job is in the default quartz group */
 @Override
 public void pauseJob(String jobId) {
   try {
     sched.pauseJob(jobKey(jobId, Scheduler.DEFAULT_GROUP));
   } catch (SchedulerException se) {
     log.error("failed to pause a job with id={}: {}", jobId, se.getMessage());
     log.debug("Exception", se);
   }
 }
Exemple #3
0
 public boolean pauseJob(JobKey jobKey) {
   try {
     if (scheduler.checkExists(jobKey)) {
       scheduler.pauseJob(jobKey);
     }
     return true;
   } catch (SchedulerException e) {
     logger.error("调度器暂停JOB异常:" + e.getMessage());
     return false;
   }
 }
  @Override
  public void pause(String jobName, String groupName, StorageType storageType)
      throws SchedulerException {

    try {
      Scheduler scheduler = getScheduler(storageType);

      jobName = fixMaxLength(jobName, _jobNameMaxLength, storageType);
      groupName = fixMaxLength(groupName, _groupNameMaxLength, storageType);

      JobKey jobKey = new JobKey(jobName, groupName);

      scheduler.pauseJob(jobKey);

      updateJobState(scheduler, jobKey, TriggerState.PAUSED, false);
    } catch (Exception e) {
      throw new SchedulerException(
          "Unable to pause job {jobName=" + jobName + ", groupName=" + groupName + "}", e);
    }
  }
 public void pauseJob(JobKey jobKey) throws SchedulerException {
   quartzScheduler.pauseJob(jobKey);
 }
Exemple #6
0
  /**
   * Test.
   *
   * @throws IOException e
   * @throws SchedulerException e
   */
  @Test
  public void testJob() throws IOException, SchedulerException {
    // job quartz
    JobGlobalListener.initJobGlobalListener();
    JobGlobalListener.getJobCounter().clear();

    // Grab the Scheduler instance from the Factory
    final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

    try {
      // and start it off
      scheduler.start();

      final Random random = new Random();

      // Define a Trigger that will fire "later"
      final JobDetail job2 = new JobDetail("job" + random.nextInt(), null, JobTestImpl.class);
      final SimpleTrigger trigger2 =
          new SimpleTrigger(
              "trigger" + random.nextInt(), null, new Date(System.currentTimeMillis() + 60000));
      trigger2.setRepeatInterval(2 * 24L * 60 * 60 * 1000);
      scheduler.scheduleJob(job2, trigger2);
      scheduler.pauseJob(job2.getName(), job2.getGroup());
      try {
        final JobDetail job3 = new JobDetail("job" + random.nextInt(), null, JobTestImpl.class);
        // cron trigger that will never fire
        final Trigger trigger3 =
            new CronTrigger("crontrigger" + random.nextInt(), null, "0 0 0 * * ? 2030");
        scheduler.scheduleJob(job3, trigger3);

        // other trigger that will never fire
        final NthIncludedDayTrigger trigger4 =
            new NthIncludedDayTrigger("nth trigger" + random.nextInt(), null);
        trigger4.setN(1);
        trigger4.setIntervalType(NthIncludedDayTrigger.INTERVAL_TYPE_YEARLY);
        trigger4.setJobName(job3.getName());
        scheduler.scheduleJob(trigger4);
      } catch (final ParseException e) {
        throw new IllegalStateException(e);
      }

      // JavaInformations doit être réinstancié pour récupérer les jobs
      // (mais "Aucun job" dans le counter)
      final List<JavaInformations> javaInformationsList2 =
          Collections.singletonList(new JavaInformations(null, true));
      final HtmlReport htmlReport =
          new HtmlReport(collector, null, javaInformationsList2, Period.TOUT, writer);
      htmlReport.toHtml(null, null);
      assertNotEmptyAndClear(writer);

      // on lance 10 jobs pour être à peu près sûr qu'il y en a un qui fait une erreur
      // (aléatoirement il y en a 2/10 qui font une erreur)
      final Map<JobDetail, SimpleTrigger> triggersByJob =
          new LinkedHashMap<JobDetail, SimpleTrigger>();
      for (int i = 0; i < 10; i++) {
        // Define a Trigger that will fire "now"
        final JobDetail job = new JobDetail("job" + random.nextInt(), null, JobTestImpl.class);
        job.setDescription("description");

        final SimpleTrigger trigger =
            new SimpleTrigger("trigger" + random.nextInt(), null, new Date());
        // Schedule the job with the trigger
        scheduler.scheduleJob(job, trigger);
        triggersByJob.put(job, trigger);
      }
      // JobTestImpl fait un sleep de 2s au plus, donc on attend les jobs pour les compter
      try {
        Thread.sleep(3000);
      } catch (final InterruptedException e) {
        throw new IllegalStateException(e);
      }

      for (final Map.Entry<JobDetail, SimpleTrigger> entry : triggersByJob.entrySet()) {
        // et on les relance pour qu'ils soient en cours
        entry.getValue().setRepeatInterval(60000);
        scheduler.scheduleJob(entry.getKey(), entry.getValue());
      }

      // JavaInformations doit être réinstancié pour récupérer les jobs
      setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, Boolean.FALSE.toString());
      final List<JavaInformations> javaInformationsList3 =
          Collections.singletonList(new JavaInformations(null, true));
      final HtmlReport htmlReport3 =
          new HtmlReport(collector, null, javaInformationsList3, Period.TOUT, writer);
      htmlReport3.toHtml(null, null);
      assertNotEmptyAndClear(writer);
    } finally {
      scheduler.shutdown();
      JobGlobalListener.getJobCounter().clear();
      JobGlobalListener.destroyJobGlobalListener();
    }
  }
  @RequestMapping("/cancelScheduledJob")
  public String cancelScheduledJob(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam("theJobName") String theJobName,
      @RequestParam("theJobGroupName") String theJobGroupName,
      @RequestParam("theTriggerName") String triggerName,
      @RequestParam("theTriggerGroupName") String triggerGroupName,
      @RequestParam("redirection") String redirection,
      ModelMap model)
      throws SchedulerException {

    scheduler.getJobDetail(theJobName, theJobGroupName);
    logger.debug("About to pause the job-->" + theJobName + "Job Group Name -->" + theJobGroupName);

    SimpleTrigger oldTrigger = (SimpleTrigger) scheduler.getTrigger(triggerName, triggerGroupName);
    if (oldTrigger != null) {
      Date startTime =
          new Date(oldTrigger.getStartTime().getTime() + oldTrigger.getRepeatInterval());
      if (triggerGroupName.equals(ExtractController.TRIGGER_GROUP_NAME)) {
        interruptQuartzJob(scheduler, theJobName, theJobGroupName);
      }

      scheduler.pauseJob(theJobName, theJobGroupName);

      SimpleTrigger newTrigger = new SimpleTrigger(triggerName, triggerGroupName);
      newTrigger.setJobName(theJobName);
      newTrigger.setJobGroup(theJobGroupName);
      newTrigger.setJobDataMap(oldTrigger.getJobDataMap());
      newTrigger.setVolatility(false);
      newTrigger.setRepeatCount(oldTrigger.getRepeatCount());
      newTrigger.setRepeatInterval(oldTrigger.getRepeatInterval());
      newTrigger.setMisfireInstruction(
          SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT);
      newTrigger.setStartTime(startTime);
      newTrigger.setRepeatInterval(oldTrigger.getRepeatInterval());

      scheduler.unscheduleJob(
          triggerName,
          triggerGroupName); // these are the jobs which are from extract data and are not not
      // required to be rescheduled.

      ArrayList<String> pageMessages = new ArrayList<String>();

      if (triggerGroupName.equals(ExtractController.TRIGGER_GROUP_NAME)) {
        scheduler.rescheduleJob(triggerName, triggerGroupName, newTrigger);

        pageMessages.add("The Job  " + theJobName + " has been cancelled");
      } else if (triggerGroupName.equals(XsltTriggerService.TRIGGER_GROUP_NAME)) {

        JobDetailBean jobDetailBean = new JobDetailBean();
        jobDetailBean.setGroup(XsltTriggerService.TRIGGER_GROUP_NAME);
        jobDetailBean.setName(newTrigger.getName());
        jobDetailBean.setJobClass(org.akaza.openclinica.job.XsltStatefulJob.class);
        jobDetailBean.setJobDataMap(newTrigger.getJobDataMap());
        jobDetailBean.setDurability(true); // need durability?
        jobDetailBean.setVolatility(false);

        scheduler.deleteJob(theJobName, theJobGroupName);
        scheduler.scheduleJob(jobDetailBean, newTrigger);
        pageMessages.add("The Job " + theJobName + "  has been rescheduled");
      }

      request.setAttribute("pageMessages", pageMessages);

      logger.debug("jobDetails>" + scheduler.getJobDetail(theJobName, theJobGroupName));
    }
    sdvUtil.forwardRequestFromController(request, response, "/pages/" + redirection);
    return null;
  }
  @Test
  public void testBasicStorageFunctions() throws Exception {
    Scheduler sched = createScheduler("testBasicStorageFunctions", 2);

    // test basic storage functions of scheduler...

    JobDetail job = newJob().ofType(TestJob.class).withIdentity("j1").storeDurably().build();

    assertFalse("Unexpected existence of job named 'j1'.", sched.checkExists(jobKey("j1")));

    sched.addJob(job, false);

    assertTrue(
        "Expected existence of job named 'j1' but checkExists return false.",
        sched.checkExists(jobKey("j1")));

    job = sched.getJobDetail(jobKey("j1"));

    assertNotNull("Stored job not found!", job);

    sched.deleteJob(jobKey("j1"));

    Trigger trigger =
        newTrigger()
            .withIdentity("t1")
            .forJob(job)
            .startNow()
            .withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(5))
            .build();

    assertFalse("Unexpected existence of trigger named 't1'.", sched.checkExists(triggerKey("t1")));

    sched.scheduleJob(job, trigger);

    assertTrue(
        "Expected existence of trigger named 't1' but checkExists return false.",
        sched.checkExists(triggerKey("t1")));

    job = sched.getJobDetail(jobKey("j1"));

    assertNotNull("Stored job not found!", job);

    trigger = sched.getTrigger(triggerKey("t1"));

    assertNotNull("Stored trigger not found!", trigger);

    job = newJob().ofType(TestJob.class).withIdentity("j2", "g1").build();

    trigger =
        newTrigger()
            .withIdentity("t2", "g1")
            .forJob(job)
            .startNow()
            .withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(5))
            .build();

    sched.scheduleJob(job, trigger);

    job = newJob().ofType(TestJob.class).withIdentity("j3", "g1").build();

    trigger =
        newTrigger()
            .withIdentity("t3", "g1")
            .forJob(job)
            .startNow()
            .withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(5))
            .build();

    sched.scheduleJob(job, trigger);

    List<String> jobGroups = sched.getJobGroupNames();
    List<String> triggerGroups = sched.getTriggerGroupNames();

    assertTrue("Job group list size expected to be = 2 ", jobGroups.size() == 2);
    assertTrue("Trigger group list size expected to be = 2 ", triggerGroups.size() == 2);

    Set<JobKey> jobKeys = sched.getJobKeys(GroupMatcher.jobGroupEquals(JobKey.DEFAULT_GROUP));
    Set<TriggerKey> triggerKeys =
        sched.getTriggerKeys(GroupMatcher.triggerGroupEquals(TriggerKey.DEFAULT_GROUP));

    assertTrue("Number of jobs expected in default group was 1 ", jobKeys.size() == 1);
    assertTrue("Number of triggers expected in default group was 1 ", triggerKeys.size() == 1);

    jobKeys = sched.getJobKeys(GroupMatcher.jobGroupEquals("g1"));
    triggerKeys = sched.getTriggerKeys(GroupMatcher.triggerGroupEquals("g1"));

    assertTrue("Number of jobs expected in 'g1' group was 2 ", jobKeys.size() == 2);
    assertTrue("Number of triggers expected in 'g1' group was 2 ", triggerKeys.size() == 2);

    TriggerState s = sched.getTriggerState(triggerKey("t2", "g1"));
    assertTrue("State of trigger t2 expected to be NORMAL ", s.equals(TriggerState.NORMAL));

    sched.pauseTrigger(triggerKey("t2", "g1"));
    s = sched.getTriggerState(triggerKey("t2", "g1"));
    assertTrue("State of trigger t2 expected to be PAUSED ", s.equals(TriggerState.PAUSED));

    sched.resumeTrigger(triggerKey("t2", "g1"));
    s = sched.getTriggerState(triggerKey("t2", "g1"));
    assertTrue("State of trigger t2 expected to be NORMAL ", s.equals(TriggerState.NORMAL));

    Set<String> pausedGroups = sched.getPausedTriggerGroups();
    assertTrue("Size of paused trigger groups list expected to be 0 ", pausedGroups.size() == 0);

    sched.pauseTriggers(GroupMatcher.triggerGroupEquals("g1"));

    // test that adding a trigger to a paused group causes the new trigger to be paused also...
    job = newJob().ofType(TestJob.class).withIdentity("j4", "g1").build();

    trigger =
        newTrigger()
            .withIdentity("t4", "g1")
            .forJob(job)
            .startNow()
            .withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(5))
            .build();

    sched.scheduleJob(job, trigger);
    // TODO: nexus hack: JobStoreImpl DOES NOT "remember" paused groups
    sched.pauseJob(jobKey("j4", "g1"));

    pausedGroups = sched.getPausedTriggerGroups();
    assertTrue(
        "Size of paused trigger groups list expected to be 1: " + pausedGroups,
        pausedGroups.size() == 1);

    s = sched.getTriggerState(triggerKey("t2", "g1"));
    assertTrue("State of trigger t2 expected to be PAUSED ", s.equals(TriggerState.PAUSED));

    s = sched.getTriggerState(triggerKey("t4", "g1"));
    assertTrue("State of trigger t4 expected to be PAUSED ", s.equals(TriggerState.PAUSED));

    sched.resumeTriggers(GroupMatcher.triggerGroupEquals("g1"));
    s = sched.getTriggerState(triggerKey("t2", "g1"));
    assertTrue("State of trigger t2 expected to be NORMAL ", s.equals(TriggerState.NORMAL));
    s = sched.getTriggerState(triggerKey("t4", "g1"));
    assertTrue("State of trigger t4 expected to be NORMAL ", s.equals(TriggerState.NORMAL));
    pausedGroups = sched.getPausedTriggerGroups();
    assertTrue("Size of paused trigger groups list expected to be 0 ", pausedGroups.size() == 0);

    assertFalse(
        "Scheduler should have returned 'false' from attempt to unschedule non-existing trigger. ",
        sched.unscheduleJob(triggerKey("foasldfksajdflk")));

    assertTrue(
        "Scheduler should have returned 'true' from attempt to unschedule existing trigger. ",
        sched.unscheduleJob(triggerKey("t3", "g1")));

    jobKeys = sched.getJobKeys(GroupMatcher.jobGroupEquals("g1"));
    triggerKeys = sched.getTriggerKeys(GroupMatcher.triggerGroupEquals("g1"));

    assertTrue(
        "Number of jobs expected in 'g1' group was 1 ",
        jobKeys.size() == 2); // job should have been deleted also, because it is non-durable
    assertTrue("Number of triggers expected in 'g1' group was 1 ", triggerKeys.size() == 2);

    assertTrue(
        "Scheduler should have returned 'true' from attempt to unschedule existing trigger. ",
        sched.unscheduleJob(triggerKey("t1")));

    jobKeys = sched.getJobKeys(GroupMatcher.jobGroupEquals(JobKey.DEFAULT_GROUP));
    triggerKeys = sched.getTriggerKeys(GroupMatcher.triggerGroupEquals(TriggerKey.DEFAULT_GROUP));

    assertTrue(
        "Number of jobs expected in default group was 1 ",
        jobKeys.size() == 1); // job should have been left in place, because it is non-durable
    assertTrue("Number of triggers expected in default group was 0 ", triggerKeys.size() == 0);

    sched.shutdown(true);
  }
  public void jobAdded(JobDetail jobDetail) {
    TrackNRestartMessageKind.ITNRPLUGIN0003.format(jobDetail.getKey());
    JobKey jobKey = jobDetail.getKey();
    JobDataMap currentJobDataMap = jobDetail.getJobDataMap();
    String restart = currentJobDataMap.getString(RESTARTED_FIRE_INSTANCE_ID);
    try {
      if (fetchJob(getNonManagedTXConnection(), jobKey)) { // group.job exists
        if (restart
            == null) { // simple tracking mode but such an initial execution of this job has already
          // been recorded
          TrackNRestartMessageKind.ITNRPLUGIN0004.format(jobKey);
          TrackNRestartMessageKind.WTNRPLUGIN0005.format(jobKey);
        } else {
          if (restart.trim().equals("_LAST_")) { // Retrieve last execution to restart it
            restart = fetchJobExecLast(getNonManagedTXConnection(), jobKey);
            if (restart != null) {

              jobDetail.getJobBuilder().usingJobData(RESTARTED_FIRE_INSTANCE_ID, restart);
              jobDetail.getJobBuilder().usingJobData(JOB_IDENTIFICATION_COMPLETE, false);

              TrackNRestartMessageKind.ITNRPLUGIN0006.format(jobKey, restart);
              scheduler.pauseJob(jobKey);
              scheduler.addJob(jobDetail, true); // WARNING recursivity !

            } else {
              breakJob(jobKey, TrackNRestartMessageKind.ETNRPLUGIN0007.format(jobKey, restart));
            }
          } else { // Retrieve numbered execution to restart it
            if (!currentJobDataMap.getBoolean(
                JOB_IDENTIFICATION_COMPLETE)) { // to break recursivity
              if (fetchJobExec(getNonManagedTXConnection(), jobKey, restart)) { // found

                JobDataMap previousJobDataMap =
                    (JobDataMap)
                        getJobExecParams(
                            getNonManagedTXConnection(),
                            jobKey,
                            restart); // retrieve JDM from job to restart

                completeWithMissingParams(currentJobDataMap, previousJobDataMap);

                jobDetail.getJobBuilder().usingJobData(JOB_IDENTIFICATION_COMPLETE, true);

                TrackNRestartMessageKind.ITNRPLUGIN0010.format(jobKey, restart);
                scheduler.addJob(jobDetail, true); // WARNING recursivity !

              } else { // not found
                breakJob(jobKey, TrackNRestartMessageKind.ETNRPLUGIN0007.format(jobKey, restart));
              }
              scheduler.resumeJob(jobKey);
            }
          }
        }
      } else { // group.job doesn't exist
        if (restart == null) { // simple tracking mode
          TrackNRestartMessageKind.ITNRPLUGIN0004.format(jobKey);
        } else { // inconsistent restarting mode
          breakJob(jobKey, TrackNRestartMessageKind.ETNRPLUGIN0013.format(jobKey, restart));
        }
      }
    } catch (TrackNRestartException e) {
      throw e;
    } catch (Exception e) {
      try {
        breakJob(jobKey, TrackNRestartMessageKind.ETNRPLUGIN0002.format(e));
        //				e.printStackTrace();
        //				scheduler.deleteJob(jobKey);
      } catch (SchedulerException e1) {
        getLog().error("Deleting " + jobKey + " caused exception.", e);
      }
    }
  }