Java Code Examples for org.quartz.spi.OperableTrigger#computeFirstFireTime()

The following examples show how to use org.quartz.spi.OperableTrigger#computeFirstFireTime() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TriggerUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a list of Dates that are the next fire times of a 
 * <code>Trigger</code>.
 * The input trigger will be cloned before any work is done, so you need
 * not worry about its state being altered by this method.
 * 
 * @param trigg
 *          The trigger upon which to do the work
 * @param cal
 *          The calendar to apply to the trigger's schedule
 * @param numTimes
 *          The number of next fire times to produce
 * @return List of java.util.Date objects
 */
public static List<Date> computeFireTimes(OperableTrigger trigg, org.quartz.Calendar cal,
        int numTimes) {
    LinkedList<Date> lst = new LinkedList<Date>();

    OperableTrigger t = (OperableTrigger) trigg.clone();

    if (t.getNextFireTime() == null) {
        t.computeFirstFireTime(cal);
    }

    for (int i = 0; i < numTimes; i++) {
        Date d = t.getNextFireTime();
        if (d != null) {
            lst.add(d);
            t.triggered(cal);
        } else {
            break;
        }
    }

    return java.util.Collections.unmodifiableList(lst);
}
 
Example 2
Source File: QuartzScheduler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>
 * Trigger the identified <code>{@link org.quartz.Job}</code> (execute it
 * now) - with a non-volatile trigger.
 * </p>
 */
@SuppressWarnings("deprecation")
public void triggerJob(JobKey jobKey, JobDataMap data) throws SchedulerException {
    validateState();

    OperableTrigger trig = (OperableTrigger) newTrigger().withIdentity(newTriggerId(), Scheduler.DEFAULT_GROUP).forJob(jobKey).build();
    trig.computeFirstFireTime(null);
    if(data != null) {
        trig.setJobDataMap(data);
    }

    boolean collision = true;
    while (collision) {
        try {
            resources.getJobStore().storeTrigger(trig, false);
            collision = false;
        } catch (ObjectAlreadyExistsException oaee) {
            trig.setKey(new TriggerKey(newTriggerId(), Scheduler.DEFAULT_GROUP));
        }
    }

    notifySchedulerThread(trig.getNextFireTime().getTime());
    notifySchedulerListenersSchduled(trig);
}
 
Example 3
Source File: QuartzScheduler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>
 * Store and schedule the identified <code>{@link org.quartz.spi.OperableTrigger}</code>
 * </p>
 */
public void triggerJob(OperableTrigger trig) throws SchedulerException {
    validateState();

    trig.computeFirstFireTime(null);

    boolean collision = true;
    while (collision) {
        try {
            resources.getJobStore().storeTrigger(trig, false);
            collision = false;
        } catch (ObjectAlreadyExistsException oaee) {
            trig.setKey(new TriggerKey(newTriggerId(), Scheduler.DEFAULT_GROUP));
        }
    }

    notifySchedulerThread(trig.getNextFireTime().getTime());
    notifySchedulerListenersSchduled(trig);
}
 
Example 4
Source File: AbstractJobStoreTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAcquireTriggersInBatch() throws Exception {
  SchedulerSignaler schedSignaler = new SampleSignaler();
  ClassLoadHelper loadHelper = new CascadingClassLoadHelper();
  loadHelper.initialize();

  JobStore store = createJobStore("testAcquireTriggersInBatch");
  store.initialize(loadHelper, schedSignaler);

  // Setup: Store jobs and triggers.
  long MIN = 60 * 1000L;
  Date startTime0 = new Date(System.currentTimeMillis() + MIN); // a min from now.
  for (int i=0; i < 10; i++) {
    Date startTime = new Date(startTime0.getTime() + i * MIN); // a min apart
    JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("job" + i).build();
    SimpleScheduleBuilder schedule = SimpleScheduleBuilder.repeatMinutelyForever(2);
    OperableTrigger trigger = (OperableTrigger)TriggerBuilder.newTrigger().withIdentity("job" + i).withSchedule(schedule).forJob(job).startAt(startTime).build();

    // Manually trigger the first fire time computation that scheduler would do. Otherwise
    // the store.acquireNextTriggers() will not work properly.
    Date fireTime = trigger.computeFirstFireTime(null);
    Assert.assertEquals(true, fireTime != null);

    store.storeJobAndTrigger(job, trigger);
  }

  // Test acquire batch of triggers at a time
  long noLaterThan = startTime0.getTime() + 10 * MIN;
  int maxCount = 7;
  // time window needs to be big to be able to pick up multiple triggers when they are a minute apart
  long timeWindow = 8 * MIN;
  List<OperableTrigger> triggers = store.acquireNextTriggers(noLaterThan, maxCount, timeWindow);
  Assert.assertEquals(7, triggers.size());
  for (int i=0; i < 7; i++) {
    Assert.assertEquals("job" + i, triggers.get(i).getKey().getName());
  }
}
 
Example 5
Source File: DefaultClusteredJobStore.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void scheduleRecoveryIfNeeded(TriggerWrapper tw, FiredTrigger recovering) {
  JobWrapper jobWrapper = jobFacade.get(tw.getJobKey());

  if (jobWrapper == null) {
    getLog().error("No job found for orphaned trigger: " + tw);
    return;
  }

  if (jobWrapper.requestsRecovery()) {
    OperableTrigger recoveryTrigger = createRecoveryTrigger(tw, jobWrapper, "recover_" + terracottaClientId + "_"
                                                                        + ftrCtr++, recovering);

    JobDataMap jd = tw.getTriggerClone().getJobDataMap();
    jd.put(Scheduler.FAILED_JOB_ORIGINAL_TRIGGER_NAME, tw.getKey().getName());
    jd.put(Scheduler.FAILED_JOB_ORIGINAL_TRIGGER_GROUP, tw.getKey().getGroup());
    jd.put(Scheduler.FAILED_JOB_ORIGINAL_TRIGGER_FIRETIME_IN_MILLISECONDS, String.valueOf(recovering.getFireTime()));
    jd.put(Scheduler.FAILED_JOB_ORIGINAL_TRIGGER_SCHEDULED_FIRETIME_IN_MILLISECONDS, String.valueOf(recovering.getScheduledFireTime()));

    recoveryTrigger.setJobDataMap(jd);
    recoveryTrigger.computeFirstFireTime(null);

    try {
      storeTrigger(recoveryTrigger, false);
      if (!tw.mayFireAgain()) {
        removeTrigger(tw.getKey());
      }
      getLog().info("Recovered job " + jobWrapper + " for trigger " + tw);
    } catch (JobPersistenceException e) {
      getLog().error("Can't recover job " + jobWrapper + " for trigger " + tw, e);
    }
  }
}
 
Example 6
Source File: AbstractJobStoreTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAcquireTriggers() throws Exception {
  SchedulerSignaler schedSignaler = new SampleSignaler();
  ClassLoadHelper loadHelper = new CascadingClassLoadHelper();
  loadHelper.initialize();

  JobStore store = createJobStore("testAcquireTriggers");
  store.initialize(loadHelper, schedSignaler);

  // Setup: Store jobs and triggers.
  long MIN = 60 * 1000L;
  Date startTime0 = new Date(System.currentTimeMillis() + MIN); // a min from now.
  for (int i=0; i < 10; i++) {
    Date startTime = new Date(startTime0.getTime() + i * MIN); // a min apart
    JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("job" + i).build();
    SimpleScheduleBuilder schedule = SimpleScheduleBuilder.repeatMinutelyForever(2);
    OperableTrigger trigger = (OperableTrigger)TriggerBuilder.newTrigger().withIdentity("job" + i).withSchedule(schedule).forJob(job).startAt(startTime).build();

    // Manually trigger the first fire time computation that scheduler would do. Otherwise
    // the store.acquireNextTriggers() will not work properly.
    Date fireTime = trigger.computeFirstFireTime(null);
    Assert.assertEquals(true, fireTime != null);

    store.storeJobAndTrigger(job, trigger);
  }

  // Test acquire one trigger at a time
  for (int i=0; i < 10; i++) {
    long noLaterThan = (startTime0.getTime() + i * MIN);
    int maxCount = 1;
    long timeWindow = 0;
    List<OperableTrigger> triggers = store.acquireNextTriggers(noLaterThan, maxCount, timeWindow);
    Assert.assertEquals(1, triggers.size());
    Assert.assertEquals("job" + i, triggers.get(0).getKey().getName());

    // Let's remove the trigger now.
    store.removeJob(triggers.get(0).getJobKey());
  }
}
 
Example 7
Source File: AbstractJobStoreTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testTriggerStates() throws Exception {
  OperableTrigger trigger =
      new SimpleTriggerImpl("trigger1", "triggerGroup1", this.fJobDetail.getName(), this.fJobDetail.getGroup(),
          new Date(System.currentTimeMillis() + 100000), new Date(System.currentTimeMillis() + 200000), 2, 2000);
  trigger.computeFirstFireTime(null);
  assertEquals(TriggerState.NONE, this.fJobStore.getTriggerState(trigger.getKey()));
  this.fJobStore.storeTrigger(trigger, false);
  assertEquals(TriggerState.NORMAL, this.fJobStore.getTriggerState(trigger.getKey()));

  this.fJobStore.pauseTrigger(trigger.getKey());
  assertEquals(TriggerState.PAUSED, this.fJobStore.getTriggerState(trigger.getKey()));

  this.fJobStore.resumeTrigger(trigger.getKey());
  assertEquals(TriggerState.NORMAL, this.fJobStore.getTriggerState(trigger.getKey()));

  trigger = this.fJobStore.acquireNextTriggers(
      new Date(trigger.getNextFireTime().getTime()).getTime() + 10000, 1, 1L).get(0);
  assertNotNull(trigger);
  this.fJobStore.releaseAcquiredTrigger(trigger);
  trigger=this.fJobStore.acquireNextTriggers(
      new Date(trigger.getNextFireTime().getTime()).getTime() + 10000, 1, 1L).get(0);
  assertNotNull(trigger);
  assertTrue(this.fJobStore.acquireNextTriggers(
      new Date(trigger.getNextFireTime().getTime()).getTime() + 10000, 1, 1L).isEmpty());
}
 
Example 8
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testResetErrorTrigger() throws Exception {
  JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("job1", "jobGroup1").storeDurably(true).build();
  this.jobStore.storeJob(jobDetail, false);
  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  long baseFireTime = baseFireTimeDate.getTime();

  // create and store a trigger
  OperableTrigger trigger1 =
      new SimpleTriggerImpl("trigger1", "triggerGroup1", jobDetail.getKey().getName(),
          jobDetail.getKey().getGroup(), new Date(baseFireTime + 200000),
          new Date(baseFireTime + 200000), 2, 2000);

  trigger1.computeFirstFireTime(null);
  jobStore.storeTrigger(trigger1, false);

  long firstFireTime = new Date(trigger1.getNextFireTime().getTime()).getTime();


  // pretend to fire it
  List<OperableTrigger> aqTs = jobStore.acquireNextTriggers(
      firstFireTime + 10000, 1, 0L);
  assertEquals(trigger1.getKey(), aqTs.get(0).getKey());

  List<TriggerFiredResult> fTs = jobStore.triggersFired(aqTs);
  TriggerFiredResult ft = fTs.get(0);

  // get the trigger into error state
  jobStore.triggeredJobComplete(ft.getTriggerFiredBundle().getTrigger(), ft.getTriggerFiredBundle().getJobDetail(),
      Trigger.CompletedExecutionInstruction.SET_TRIGGER_ERROR);
  TriggerState state = jobStore.getTriggerState(trigger1.getKey());
  assertEquals(TriggerState.ERROR, state);

  // test reset
  jobStore.resetTriggerFromErrorState(trigger1.getKey());
  state = jobStore.getTriggerState(trigger1.getKey());
  assertEquals(TriggerState.NORMAL, state);
}
 
Example 9
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAcquireTriggers() throws Exception {
  // Setup: Store jobs and triggers.
  long MIN = 60 * 1000L;
  Date startTime0 = new Date(System.currentTimeMillis() + MIN); // a min from now.
  for (int i = 0; i < 10; i++) {
    Date startTime = new Date(startTime0.getTime() + i * MIN); // a min apart
    JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("job" + i).build();
    SimpleScheduleBuilder schedule = SimpleScheduleBuilder.repeatMinutelyForever(2);
    OperableTrigger trigger = (OperableTrigger) TriggerBuilder.newTrigger().withIdentity("job" + i)
        .withSchedule(schedule).forJob(job).startAt(startTime).build();

    // Manually trigger the first fire time computation that scheduler would do. Otherwise
    // the store.acquireNextTriggers() will not work properly.
    Date fireTime = trigger.computeFirstFireTime(null);
    assertEquals(true, fireTime != null);

    jobStore.storeJobAndTrigger(job, trigger);
  }

  // Test acquire one trigger at a time
  for (int i = 0; i < 10; i++) {
    long noLaterThan = (startTime0.getTime() + i * MIN);
    int maxCount = 1;
    long timeWindow = 0;
    List<OperableTrigger> triggers = jobStore.acquireNextTriggers(noLaterThan, maxCount, timeWindow);
    assertEquals(1, triggers.size());
    assertEquals("job" + i, triggers.get(0).getKey().getName());

    // Let's remove the trigger now.
    jobStore.removeJob(triggers.get(0).getJobKey());
  }
}
 
Example 10
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testTriggerStates() throws Exception {
  JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("job1", "jobGroup1").storeDurably(true).build();
  this.jobStore.storeJob(jobDetail, false);

  OperableTrigger trigger =
      new SimpleTriggerImpl("trigger1", "triggerGroup1", jobDetail.getKey().getName(), jobDetail.getKey().getGroup(),
          new Date(System.currentTimeMillis() + 100000), new Date(System.currentTimeMillis() + 200000), 2, 2000);
  trigger.computeFirstFireTime(null);
  assertEquals(TriggerState.NONE, this.jobStore.getTriggerState(trigger.getKey()));
  this.jobStore.storeTrigger(trigger, false);
  assertEquals(TriggerState.NORMAL, this.jobStore.getTriggerState(trigger.getKey()));

  this.jobStore.pauseTrigger(trigger.getKey());
  assertEquals(TriggerState.PAUSED, this.jobStore.getTriggerState(trigger.getKey()));

  this.jobStore.resumeTrigger(trigger.getKey());
  assertEquals(TriggerState.NORMAL, this.jobStore.getTriggerState(trigger.getKey()));

  trigger = this.jobStore.acquireNextTriggers(
      new Date(trigger.getNextFireTime().getTime()).getTime() + 10000, 1, 1L).get(0);
  assertNotNull(trigger);
  this.jobStore.releaseAcquiredTrigger(trigger);
  trigger = this.jobStore.acquireNextTriggers(
      new Date(trigger.getNextFireTime().getTime()).getTime() + 10000, 1, 1L).get(0);
  assertNotNull(trigger);
  assertTrue(this.jobStore.acquireNextTriggers(
      new Date(trigger.getNextFireTime().getTime()).getTime() + 10000, 1, 1L).isEmpty());
}
 
Example 11
Source File: SimpleScheduleJobService.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
public static List<Date> computeFireTimesBetween(OperableTrigger trigger,
                                                 org.quartz.Calendar cal, Date from, Date to, int num) {
    List<Date> lst = new LinkedList<>();
    OperableTrigger t = (OperableTrigger) trigger.clone();
    if (t.getNextFireTime() == null) {
        t.setStartTime(from);
        t.setEndTime(to);
        t.computeFirstFireTime(cal);
    }
    for (int i = 0; i < num; i++) {
        Date d = t.getNextFireTime();
        if (d != null) {
            if (d.before(from)) {
                t.triggered(cal);
                continue;
            }
            if (d.after(to)) {
                break;
            }
            lst.add(d);
            t.triggered(cal);
        } else {
            break;
        }
    }
    return lst;
}
 
Example 12
Source File: TaskNode.java    From uflo with Apache License 2.0 5 votes vote down vote up
public static Date computeFireTimesWithStart(OperableTrigger trigg,org.quartz.Calendar cal, Date from) {
    OperableTrigger t = (OperableTrigger) trigg.clone();
    if (t.getNextFireTime() == null) {
        t.setStartTime(from);
        t.computeFirstFireTime(cal);
    }
    return t.getNextFireTime();
}
 
Example 13
Source File: AbstractJobStoreTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testResetErrorTrigger() throws Exception {

  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  long baseFireTime = baseFireTimeDate.getTime();

  // create and store a trigger
  OperableTrigger trigger1 =
      new SimpleTriggerImpl("trigger1", "triggerGroup1", this.fJobDetail.getName(),
          this.fJobDetail.getGroup(), new Date(baseFireTime + 200000),
          new Date(baseFireTime + 200000), 2, 2000);

  trigger1.computeFirstFireTime(null);
  this.fJobStore.storeTrigger(trigger1, false);

  long firstFireTime = new Date(trigger1.getNextFireTime().getTime()).getTime();


  // pretend to fire it
  List<OperableTrigger> aqTs = this.fJobStore.acquireNextTriggers(
      firstFireTime + 10000, 1, 0L);
  assertEquals(trigger1.getKey(), aqTs.get(0).getKey());

  List<TriggerFiredResult> fTs = this.fJobStore.triggersFired(aqTs);
  TriggerFiredResult ft = fTs.get(0);

  // get the trigger into error state
  this.fJobStore.triggeredJobComplete(ft.getTriggerFiredBundle().getTrigger(), ft.getTriggerFiredBundle().getJobDetail(), Trigger.CompletedExecutionInstruction.SET_TRIGGER_ERROR);
  TriggerState state = this.fJobStore.getTriggerState(trigger1.getKey());
  assertEquals(TriggerState.ERROR, state);

  // test reset
  this.fJobStore.resetTriggerFromErrorState(trigger1.getKey());
  state = this.fJobStore.getTriggerState(trigger1.getKey());
  assertEquals(TriggerState.NORMAL, state);
}
 
Example 14
Source File: QuartzScheduler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>
 * Schedule the given <code>{@link org.quartz.Trigger}</code> with the
 * <code>Job</code> identified by the <code>Trigger</code>'s settings.
 * </p>
 * 
 * @throws SchedulerException
 *           if the indicated Job does not exist, or the Trigger cannot be
 *           added to the Scheduler, or there is an internal Scheduler
 *           error.
 */
public Date scheduleJob(Trigger trigger)
    throws SchedulerException {
    validateState();

    if (trigger == null) {
        throw new SchedulerException("Trigger cannot be null");
    }

    OperableTrigger trig = (OperableTrigger)trigger;
    
    trig.validate();

    Calendar cal = null;
    if (trigger.getCalendarName() != null) {
        cal = resources.getJobStore().retrieveCalendar(trigger.getCalendarName());
        if(cal == null) {
            throw new SchedulerException(
                "Calendar not found: " + trigger.getCalendarName());
        }
    }
    Date ft = trig.computeFirstFireTime(cal);

    if (ft == null) {
        throw new SchedulerException(
                "Based on configured schedule, the given trigger '" + trigger.getKey() + "' will never fire.");
    }

    resources.getJobStore().storeTrigger(trig, false);
    notifySchedulerThread(trigger.getNextFireTime().getTime());
    notifySchedulerListenersSchduled(trigger);

    return ft;
}
 
Example 15
Source File: TriggerUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a list of Dates that are the next fire times of a 
 * <code>Trigger</code>
 * that fall within the given date range. The input trigger will be cloned
 * before any work is done, so you need not worry about its state being
 * altered by this method.
 * 
 * <p>
 * NOTE: if this is a trigger that has previously fired within the given
 * date range, then firings which have already occurred will not be listed
 * in the output List.
 * </p>
 * 
 * @param trigg
 *          The trigger upon which to do the work
 * @param cal
 *          The calendar to apply to the trigger's schedule
 * @param from
 *          The starting date at which to find fire times
 * @param to
 *          The ending date at which to stop finding fire times
 * @return List of java.util.Date objects
 */
public static List<Date> computeFireTimesBetween(OperableTrigger trigg,
        org.quartz.Calendar cal, Date from, Date to) {
    LinkedList<Date> lst = new LinkedList<Date>();

    OperableTrigger t = (OperableTrigger) trigg.clone();

    if (t.getNextFireTime() == null) {
        t.setStartTime(from);
        t.setEndTime(to);
        t.computeFirstFireTime(cal);
    }

    while (true) {
        Date d = t.getNextFireTime();
        if (d != null) {
            if (d.before(from)) {
                t.triggered(cal);
                continue;
            }
            if (d.after(to)) {
                break;
            }
            lst.add(d);
            t.triggered(cal);
        } else {
            break;
        }
    }

    return java.util.Collections.unmodifiableList(lst);
}
 
Example 16
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
private void testTriggerAcquiredCorrectly(State initialState, boolean isOrphaned, boolean shouldBeAcquired) throws Exception  {
  when(nodeAccess.isClustered()).thenReturn(true);
  when(nodeAccess.getId()).thenReturn(isOrphaned ? "C" : "A");
  when(nodeAccess.getMemberIds()).thenReturn(Sets.newHashSet("A", "B"));

  JobDetail orphanedJob = newJob()
      .ofType(MyJob.class)
      .withIdentity("jobName1", "jobGroup1")
      .build();

  OperableTrigger orphanedTrigger = (OperableTrigger) newTrigger()
      .forJob(orphanedJob)
      .withIdentity("orphan:" + isOrphaned, "state:" + initialState.name())
      .startNow()
      .build();

  orphanedTrigger.computeFirstFireTime(null);

  this.jobStore.storeTrigger(orphanedTrigger, false);

  Iterator<TriggerEntity> triggerEntities = inTx(database.getInstanceProvider())
      .throwing(JobPersistenceException.class)
      .call(db -> triggerEntityAdapter.browseByJobKey(db, orphanedJob.getKey())).iterator();

  assertTrue(triggerEntities.hasNext());
  TriggerEntity entity = triggerEntities.next();
  entity.setState(initialState);

  inTx(database.getInstanceProvider())
      .throwing(JobPersistenceException.class)
      .call(db -> triggerEntityAdapter.editEntity(db, entity));

  long firstFireTime = orphanedTrigger.getNextFireTime().getTime();

  when(nodeAccess.getId()).thenReturn("A");

  List<OperableTrigger> acquiredTriggers = this.jobStore.acquireNextTriggers(firstFireTime + 10000, 10, 1L);

  if (shouldBeAcquired) {
    assertEquals(1 , acquiredTriggers.size());
    assertTrue(orphanedTrigger.equals(acquiredTriggers.get(0)));
  } else {
    assertEquals(0, acquiredTriggers.size());
  }

  jobStore.removeJob(orphanedJob.getKey());
}
 
Example 17
Source File: JobStoreImplTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testAcquireNextTrigger() throws Exception {
  JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("job1", "jobGroup1").storeDurably(true).build();
  this.jobStore.storeJob(jobDetail, false);

  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  long baseFireTime = baseFireTimeDate.getTime();

  OperableTrigger trigger1 =
      new SimpleTriggerImpl("trigger1", "triggerGroup1", jobDetail.getKey().getName(),
          jobDetail.getKey().getGroup(), new Date(baseFireTime + 200000),
          new Date(baseFireTime + 200000), 2, 2000);
  OperableTrigger trigger2 =
      new SimpleTriggerImpl("trigger2", "triggerGroup1", jobDetail.getKey().getName(),
          jobDetail.getKey().getGroup(), new Date(baseFireTime + 50000),
          new Date(baseFireTime + 200000), 2, 2000);
  OperableTrigger trigger3 =
      new SimpleTriggerImpl("trigger1", "triggerGroup2", jobDetail.getKey().getName(),
          jobDetail.getKey().getGroup(), new Date(baseFireTime + 100000),
          new Date(baseFireTime + 200000), 2, 2000);

  trigger1.computeFirstFireTime(null);
  trigger2.computeFirstFireTime(null);
  trigger3.computeFirstFireTime(null);
  this.jobStore.storeTrigger(trigger1, false);
  this.jobStore.storeTrigger(trigger2, false);
  this.jobStore.storeTrigger(trigger3, false);

  long firstFireTime = new Date(trigger1.getNextFireTime().getTime()).getTime();

  assertTrue(this.jobStore.acquireNextTriggers(10, 1, 0L).isEmpty());
  assertEquals(
      trigger2.getKey(),
      this.jobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertEquals(
      trigger3.getKey(),
      this.jobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertEquals(
      trigger1.getKey(),
      this.jobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertTrue(
      this.jobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).isEmpty());


  // release trigger3
  this.jobStore.releaseAcquiredTrigger(trigger3);
  assertEquals(
      trigger3,
      this.jobStore.acquireNextTriggers(new Date(trigger1.getNextFireTime().getTime()).getTime() + 10000, 1, 1L)
          .get(0));
}
 
Example 18
Source File: AbstractQuartzTaskManager.java    From carbon-commons with Apache License 2.0 4 votes vote down vote up
protected synchronized void scheduleLocalTask(String taskName,
                                              boolean paused) throws TaskException {
    TaskInfo taskInfo = this.getTaskRepository().getTask(taskName);
    String taskGroup = this.getTenantTaskGroup();
    if (taskInfo == null) {
        throw new TaskException("Non-existing task for scheduling with name: " + taskName,
                Code.NO_TASK_EXISTS);
    }
    if (this.containsLocalTask(taskName, taskGroup)) {
        /* to make the scheduleLocalTask operation idempotent */
        return;
    }
    Class<? extends Job> jobClass = taskInfo.getTriggerInfo().isDisallowConcurrentExecution() ?
            NonConcurrentTaskQuartzJobAdapter.class : TaskQuartzJobAdapter.class;
    JobDetail job = JobBuilder.newJob(jobClass).withIdentity(taskName, taskGroup).usingJobData(
            this.getJobDataMapFromTaskInfo(taskInfo)).build();
    Trigger trigger = this.getTriggerFromInfo(taskName, taskGroup, taskInfo.getTriggerInfo());
    try {
        if (trigger instanceof CronTriggerImpl) {
            OperableTrigger trig = (OperableTrigger) trigger;
            Calendar cal = null;
            if (trigger.getCalendarName() != null) {
                scheduler.getCalendar(trigger.getCalendarName());
            }
            Date ft = trig.computeFirstFireTime(cal);
            if (ft == null) {
                log.info("Task [" + this.getTenantId() + "][" +
                        this.getTaskType() + "][" + taskName + "] not scheduled as given trigger will never fire");
            } else {
                this.getScheduler().scheduleJob(job, trigger);
                if (paused) {
                    this.getScheduler().pauseJob(job.getKey());
                }
                log.info("Task scheduled: [" + this.getTenantId() +
                        "][" + this.getTaskType() + "][" + taskName + "]" + (paused ? "[Paused]" : ""));
            }
        } else {
            this.getScheduler().scheduleJob(job, trigger);
            if (paused) {
                this.getScheduler().pauseJob(job.getKey());
            }
            log.info("Task scheduled: [" + this.getTenantId() +
                    "][" + this.getTaskType() + "][" + taskName + "]" + (paused ? "[Paused]" : ""));
        }
    } catch (SchedulerException e) {
        throw new TaskException("Error in scheduling task with name: " + taskName,
                Code.UNKNOWN, e);
    }    
}
 
Example 19
Source File: AbstractJobStoreTest.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testAcquireNextTrigger() throws Exception {

  Date baseFireTimeDate = DateBuilder.evenMinuteDateAfterNow();
  long baseFireTime = baseFireTimeDate.getTime();

  OperableTrigger trigger1 =
      new SimpleTriggerImpl("trigger1", "triggerGroup1", this.fJobDetail.getName(),
          this.fJobDetail.getGroup(), new Date(baseFireTime + 200000),
          new Date(baseFireTime + 200000), 2, 2000);
  OperableTrigger trigger2 =
      new SimpleTriggerImpl("trigger2", "triggerGroup1", this.fJobDetail.getName(),
          this.fJobDetail.getGroup(), new Date(baseFireTime +  50000),
          new Date(baseFireTime + 200000), 2, 2000);
  OperableTrigger trigger3 =
      new SimpleTriggerImpl("trigger1", "triggerGroup2", this.fJobDetail.getName(),
          this.fJobDetail.getGroup(), new Date(baseFireTime + 100000),
          new Date(baseFireTime + 200000), 2, 2000);

  trigger1.computeFirstFireTime(null);
  trigger2.computeFirstFireTime(null);
  trigger3.computeFirstFireTime(null);
  this.fJobStore.storeTrigger(trigger1, false);
  this.fJobStore.storeTrigger(trigger2, false);
  this.fJobStore.storeTrigger(trigger3, false);

  long firstFireTime = new Date(trigger1.getNextFireTime().getTime()).getTime();

  assertTrue(this.fJobStore.acquireNextTriggers(10, 1, 0L).isEmpty());
  assertEquals(
      trigger2.getKey(),
      this.fJobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertEquals(
      trigger3.getKey(),
      this.fJobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertEquals(
      trigger1.getKey(),
      this.fJobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).get(0).getKey());
  assertTrue(
      this.fJobStore.acquireNextTriggers(firstFireTime + 10000, 1, 0L).isEmpty());


  // release trigger3
  this.fJobStore.releaseAcquiredTrigger(trigger3);
  assertEquals(
      trigger3,
      this.fJobStore.acquireNextTriggers(new Date(trigger1.getNextFireTime().getTime()).getTime() + 10000, 1, 1L).get(0));
}
 
Example 20
Source File: QuartzScheduler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>
 * Add the <code>{@link org.quartz.Job}</code> identified by the given
 * <code>{@link org.quartz.JobDetail}</code> to the Scheduler, and
 * associate the given <code>{@link org.quartz.Trigger}</code> with it.
 * </p>
 * 
 * <p>
 * If the given Trigger does not reference any <code>Job</code>, then it
 * will be set to reference the Job passed with it into this method.
 * </p>
 * 
 * @throws SchedulerException
 *           if the Job or Trigger cannot be added to the Scheduler, or
 *           there is an internal Scheduler error.
 */
public Date scheduleJob(JobDetail jobDetail,
        Trigger trigger) throws SchedulerException {
    validateState();

    if (jobDetail == null) {
        throw new SchedulerException("JobDetail cannot be null");
    }
    
    if (trigger == null) {
        throw new SchedulerException("Trigger cannot be null");
    }
    
    if (jobDetail.getKey() == null) {
        throw new SchedulerException("Job's key cannot be null");
    }

    if (jobDetail.getJobClass() == null) {
        throw new SchedulerException("Job's class cannot be null");
    }
    
    OperableTrigger trig = (OperableTrigger)trigger;

    if (trigger.getJobKey() == null) {
        trig.setJobKey(jobDetail.getKey());
    } else if (!trigger.getJobKey().equals(jobDetail.getKey())) {
        throw new SchedulerException(
            "Trigger does not reference given job!");
    }

    trig.validate();

    Calendar cal = null;
    if (trigger.getCalendarName() != null) {
        cal = resources.getJobStore().retrieveCalendar(trigger.getCalendarName());
    }
    Date ft = trig.computeFirstFireTime(cal);

    if (ft == null) {
        throw new SchedulerException(
                "Based on configured schedule, the given trigger '" + trigger.getKey() + "' will never fire.");
    }

    resources.getJobStore().storeJobAndTrigger(jobDetail, trig);
    notifySchedulerListenersJobAdded(jobDetail);
    notifySchedulerThread(trigger.getNextFireTime().getTime());
    notifySchedulerListenersSchduled(trigger);

    return ft;
}