org.quartz.spi.TriggerFiredResult Java Examples

The following examples show how to use org.quartz.spi.TriggerFiredResult. 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: AbstractTerracottaJobStore.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<TriggerFiredResult> triggersFired(List<OperableTrigger> triggers) throws JobPersistenceException {
  try {
    return realJobStore.triggersFired(triggers);
  } catch (RejoinException e) {
    throw new JobPersistenceException("Trigger fire marking failed due to client rejoin", e);
  }
}
 
Example #2
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 #3
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 #4
Source File: PlainTerracottaJobStore.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public List<TriggerFiredResult> triggersFired(final List<OperableTrigger> triggers) throws JobPersistenceException {
  return clusteredJobStore.triggersFired(triggers);
}
 
Example #5
Source File: RAMJobStore.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>
 * Inform the <code>JobStore</code> that the scheduler is now firing the
 * given <code>Trigger</code> (executing its associated <code>Job</code>),
 * that it had previously acquired (reserved).
 * </p>
 */
public List<TriggerFiredResult> triggersFired(List<OperableTrigger> firedTriggers) {

    synchronized (lock) {
        List<TriggerFiredResult> results = new ArrayList<TriggerFiredResult>();

        for (OperableTrigger trigger : firedTriggers) {
            TriggerWrapper tw = triggersByKey.get(trigger.getKey());
            // was the trigger deleted since being acquired?
            if (tw == null || tw.trigger == null) {
                continue;
            }
            // was the trigger completed, paused, blocked, etc. since being acquired?
            if (tw.state != TriggerWrapper.STATE_ACQUIRED) {
                continue;
            }

            Calendar cal = null;
            if (tw.trigger.getCalendarName() != null) {
                cal = retrieveCalendar(tw.trigger.getCalendarName());
                if(cal == null)
                    continue;
            }
            Date prevFireTime = trigger.getPreviousFireTime();
            // in case trigger was replaced between acquiring and firing
            timeTriggers.remove(tw);
            // call triggered on our copy, and the scheduler's copy
            tw.trigger.triggered(cal);
            trigger.triggered(cal);
            //tw.state = TriggerWrapper.STATE_EXECUTING;
            tw.state = TriggerWrapper.STATE_WAITING;

            TriggerFiredBundle bndle = new TriggerFiredBundle(retrieveJob(
                    tw.jobKey), trigger, cal,
                    false, new Date(), trigger.getPreviousFireTime(), prevFireTime,
                    trigger.getNextFireTime());

            JobDetail job = bndle.getJobDetail();

            if (job.isConcurrentExectionDisallowed()) {
                ArrayList<TriggerWrapper> trigs = getTriggerWrappersForJob(job.getKey());
                for (TriggerWrapper ttw : trigs) {
                    if (ttw.state == TriggerWrapper.STATE_WAITING) {
                        ttw.state = TriggerWrapper.STATE_BLOCKED;
                    }
                    if (ttw.state == TriggerWrapper.STATE_PAUSED) {
                        ttw.state = TriggerWrapper.STATE_PAUSED_BLOCKED;
                    }
                    timeTriggers.remove(ttw);
                }
                blockedJobs.add(job.getKey());
            } else if (tw.trigger.getNextFireTime() != null) {
                synchronized (lock) {
                    timeTriggers.add(tw);
                }
            }

            results.add(new TriggerFiredResult(bndle));
        }
        return results;
    }
}
 
Example #6
Source File: RedisClusterStorage.java    From quartz-redis-jobstore with Apache License 2.0 4 votes vote down vote up
/**
 * Inform the <code>JobStore</code> that the scheduler is now firing the
 * given <code>Trigger</code> (executing its associated <code>Job</code>),
 * that it had previously acquired (reserved).
 *
 * @param triggers a list of triggers
 * @param jedis    a thread-safe Redis connection
 * @return may return null if all the triggers or their calendars no longer exist, or
 * if the trigger was not successfully put into the 'executing'
 * state.  Preference is to return an empty list if none of the triggers
 * could be fired.
 */
@Override
public List<TriggerFiredResult> triggersFired(List<OperableTrigger> triggers, JedisClusterCommandsWrapper jedis) throws JobPersistenceException, ClassNotFoundException {
    List<TriggerFiredResult> results = new ArrayList<>();
    for (OperableTrigger trigger : triggers) {
        final String triggerHashKey = redisSchema.triggerHashKey(trigger.getKey());
        logger.debug(String.format("Trigger %s fired.", triggerHashKey));
        Boolean triggerExistsResponse = jedis.exists(triggerHashKey);
        Double triggerAcquiredResponse = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey);
        if (!triggerExistsResponse || triggerAcquiredResponse == null) {
            // the trigger does not exist or the trigger is not acquired
            if (!triggerExistsResponse) {
                logger.debug(String.format("Trigger %s does not exist.", triggerHashKey));
            } else {
                logger.debug(String.format("Trigger %s was not acquired.", triggerHashKey));
            }
            continue;
        }
        Calendar calendar = null;
        final String calendarName = trigger.getCalendarName();
        if (calendarName != null) {
            calendar = retrieveCalendar(calendarName, jedis);
            if (calendar == null) {
                continue;
            }
        }

        final Date previousFireTime = trigger.getPreviousFireTime();
        trigger.triggered(calendar);

        JobDetail job = retrieveJob(trigger.getJobKey(), jedis);
        TriggerFiredBundle triggerFiredBundle = new TriggerFiredBundle(job, trigger, calendar, false, new Date(), previousFireTime, previousFireTime, trigger.getNextFireTime());

        // handling jobs for which concurrent execution is disallowed
        if (isJobConcurrentExecutionDisallowed(job.getJobClass())) {
            final String jobHashKey = redisSchema.jobHashKey(trigger.getJobKey());
            final String jobTriggerSetKey = redisSchema.jobTriggersSetKey(job.getKey());
            for (String nonConcurrentTriggerHashKey : jedis.smembers(jobTriggerSetKey)) {
                Double score = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.WAITING), nonConcurrentTriggerHashKey);
                if (score != null) {
                    setTriggerState(RedisTriggerState.BLOCKED, score, nonConcurrentTriggerHashKey, jedis);
                    // setting trigger state removes locks, so re-lock
                    lockTrigger(redisSchema.triggerKey(nonConcurrentTriggerHashKey), jedis);
                } else {
                    score = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.PAUSED), nonConcurrentTriggerHashKey);
                    if (score != null) {
                        setTriggerState(RedisTriggerState.PAUSED_BLOCKED, score, nonConcurrentTriggerHashKey, jedis);
                        // setting trigger state removes locks, so re-lock
                        lockTrigger(redisSchema.triggerKey(nonConcurrentTriggerHashKey), jedis);
                    }
                }
            }
            jedis.set(redisSchema.jobBlockedKey(job.getKey()), schedulerInstanceId);
            jedis.sadd(redisSchema.blockedJobsSet(), jobHashKey);
        }

        // release the fired trigger
        if (trigger.getNextFireTime() != null) {
            final long nextFireTime = trigger.getNextFireTime().getTime();
            jedis.hset(triggerHashKey, TRIGGER_NEXT_FIRE_TIME, Long.toString(nextFireTime));
            logger.debug(String.format("Releasing trigger %s with next fire time %s. Setting state to WAITING.", triggerHashKey, nextFireTime));
            setTriggerState(RedisTriggerState.WAITING, (double) nextFireTime, triggerHashKey, jedis);
        } else {
            jedis.hset(triggerHashKey, TRIGGER_NEXT_FIRE_TIME, "");
            unsetTriggerState(triggerHashKey, jedis);
        }
        jedis.hset(triggerHashKey, TRIGGER_PREVIOUS_FIRE_TIME, Long.toString(System.currentTimeMillis()));

        results.add(new TriggerFiredResult(triggerFiredBundle));
    }
    return results;
}
 
Example #7
Source File: StoreTriggerTest.java    From quartz-redis-jobstore with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void triggersFired() throws Exception {
    // store some jobs with triggers
    Map<JobDetail, Set<? extends Trigger>> jobsAndTriggers = getJobsAndTriggers(2, 2, 2, 2, "* * * * * ?");

    // disallow concurrent execution for one of the jobs
    Map.Entry<JobDetail, Set<? extends Trigger>> firstEntry = jobsAndTriggers.entrySet().iterator().next();
    JobDetail nonConcurrentKey = firstEntry.getKey().getJobBuilder().ofType(TestJobNonConcurrent.class).build();
    Set<? extends Trigger> nonConcurrentTriggers = firstEntry.getValue();
    jobsAndTriggers.remove(firstEntry.getKey());
    jobsAndTriggers.put(nonConcurrentKey, nonConcurrentTriggers);

    jobStore.storeCalendar("testCalendar", new WeeklyCalendar(), false, true);
    jobStore.storeJobsAndTriggers(jobsAndTriggers, false);

    List<OperableTrigger> acquiredTriggers = jobStore.acquireNextTriggers(System.currentTimeMillis() - 1000, 500, 4000);
    assertThat(acquiredTriggers, hasSize(13));

    int lockedTriggers = 0;
    // ensure that all triggers are in the NORMAL state and have been ACQUIRED
    for (Map.Entry<JobDetail, Set<? extends Trigger>> jobDetailSetEntry : jobsAndTriggers.entrySet()) {
        for (Trigger trigger : jobDetailSetEntry.getValue()) {
            assertEquals(Trigger.TriggerState.NORMAL, jobStore.getTriggerState(trigger.getKey()));
            String triggerHashKey = schema.triggerHashKey(trigger.getKey());
            if (jobDetailSetEntry.getKey().isConcurrentExectionDisallowed()) {
                if (jedis.zscore(schema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey) != null) {
                    assertThat("acquired trigger should be locked", jedis.get(schema.triggerLockKey(schema.triggerKey(triggerHashKey))), notNullValue());
                    lockedTriggers++;
                } else {
                    assertThat("non-acquired trigger should not be locked", jedis.get(schema.triggerLockKey(schema.triggerKey(triggerHashKey))), nullValue());
                }
            } else {
                assertThat(jedis.zscore(schema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey), not(nullValue()));
            }
        }
    }

    assertThat(lockedTriggers, equalTo(1));

    Set<? extends OperableTrigger> triggers = (Set<? extends  OperableTrigger>) new ArrayList<>(jobsAndTriggers.entrySet()).get(0).getValue();
    List<TriggerFiredResult> triggerFiredResults = jobStore.triggersFired(new ArrayList<>(triggers));
    assertThat("exactly one trigger fired for job with concurrent execution disallowed", triggerFiredResults, hasSize(1));

    triggers = (Set<? extends  OperableTrigger>) new ArrayList<>(jobsAndTriggers.entrySet()).get(1).getValue();
    triggerFiredResults = jobStore.triggersFired(new ArrayList<>(triggers));
    assertThat("all triggers fired for job with concurrent execution allowed", triggerFiredResults, hasSize(4));
}
 
Example #8
Source File: RedisJobStore.java    From redis-quartz with MIT License 4 votes vote down vote up
@Override
public List<TriggerFiredResult> triggersFired(List<OperableTrigger> triggers)
		throws JobPersistenceException {
     List<TriggerFiredResult> results = new ArrayList<>();
     try (Jedis jedis = pool.getResource()) {
        lockPool.acquire();
		
		for (OperableTrigger trigger : triggers) {
			String triggerHashKey = createTriggerHashKey(trigger.getKey().getGroup(), trigger.getKey().getName());
			log.debug("trigger: " + triggerHashKey + " fired");
			
			if (!jedis.exists(triggerHashKey))
				continue; // the trigger does not exist
			
			if (jedis.zscore(RedisTriggerState.ACQUIRED.getKey(), triggerHashKey) == null)
				continue; // the trigger is not acquired

           Calendar cal = null;
			if (trigger.getCalendarName() != null) {
              String calendarName = trigger.getCalendarName();
				cal = retrieveCalendar(calendarName, jedis);
                   if(cal == null)
                       continue;
               }
               
               Date prevFireTime = trigger.getPreviousFireTime();
               trigger.triggered(cal);

               TriggerFiredBundle bundle = new TriggerFiredBundle(retrieveJob(trigger.getJobKey(), jedis), trigger, cal, false, new Date(), trigger.getPreviousFireTime(), prevFireTime, trigger.getNextFireTime());
               
               // handling job concurrent execution disallowed
               String jobHashKey = createJobHashKey(trigger.getJobKey().getGroup(), trigger.getJobKey().getName());
               if (isJobConcurrentExectionDisallowed(jedis.hget(jobHashKey, JOB_CLASS))) {
               	String jobTriggerSetKey = createJobTriggersSetKey(trigger.getJobKey().getGroup(), trigger.getJobKey().getName());
               	Set<String> nonConcurrentTriggerHashKeys = jedis.smembers(jobTriggerSetKey);
               	for (String nonConcurrentTriggerHashKey : nonConcurrentTriggerHashKeys) {
               		Double score = jedis.zscore(RedisTriggerState.WAITING.getKey(), nonConcurrentTriggerHashKey);
               		if (score != null) {
               			setTriggerState(RedisTriggerState.BLOCKED, score, nonConcurrentTriggerHashKey);
               		} else {
               			score = jedis.zscore(RedisTriggerState.PAUSED.getKey(), nonConcurrentTriggerHashKey);
               			if (score != null)
               				setTriggerState(RedisTriggerState.PAUSED_BLOCKED, score, nonConcurrentTriggerHashKey);
               		}                			
               	}
               	
               	jedis.hset(jobHashKey, BLOCKED_BY, instanceId);
               	jedis.hset(jobHashKey, BLOCK_TIME, Long.toString(System.currentTimeMillis()));
               	jedis.sadd(BLOCKED_JOBS_SET, jobHashKey);
               }
               
               // releasing the fired trigger
       		if (trigger.getNextFireTime() != null) {
       			jedis.hset(triggerHashKey, NEXT_FIRE_TIME, Long.toString(trigger.getNextFireTime().getTime()));
       			setTriggerState(RedisTriggerState.WAITING, (double)trigger.getNextFireTime().getTime(), triggerHashKey);
       		} else {
       			jedis.hset(triggerHashKey, NEXT_FIRE_TIME, "");
       			unsetTriggerState(triggerHashKey);
       		}
               
               results.add(new TriggerFiredResult(bundle));			
		}
     } catch (JobPersistenceException | ClassNotFoundException | InterruptedException ex) {
		log.error("could not acquire next triggers", ex);
		throw new JobPersistenceException(ex.getMessage(), ex.getCause());
	} finally {
        lockPool.release();
	}
	return results;		
}
 
Example #9
Source File: AbstractRedisStorage.java    From quartz-redis-jobstore with Apache License 2.0 2 votes vote down vote up
/**
 * Inform the <code>JobStore</code> that the scheduler is now firing the
 * given <code>Trigger</code> (executing its associated <code>Job</code>),
 * that it had previously acquired (reserved).
 * @param triggers a list of triggers
 * @param jedis a thread-safe Redis connection
 * @return may return null if all the triggers or their calendars no longer exist, or
 * if the trigger was not successfully put into the 'executing'
 * state.  Preference is to return an empty list if none of the triggers
 * could be fired.
 */
public abstract List<TriggerFiredResult> triggersFired(List<OperableTrigger> triggers, T jedis) throws JobPersistenceException, ClassNotFoundException;