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

The following examples show how to use org.quartz.spi.OperableTrigger#getNextFireTime() . 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: RedisJobStore.java    From redis-quartz with MIT License 6 votes vote down vote up
@Override
  public void releaseAcquiredTrigger(OperableTrigger trigger) {
     try (Jedis jedis = pool.getResource()) {
        lockPool.acquire();
		
		String triggerHashKey = createTriggerHashKey(trigger.getKey().getGroup(), trigger.getKey().getName());
		if (jedis.zscore(RedisTriggerState.ACQUIRED.getKey(), triggerHashKey) != null) {
			if (trigger.getNextFireTime() != null)
				setTriggerState(RedisTriggerState.WAITING, (double)trigger.getNextFireTime().getTime(), triggerHashKey);
			else
				unsetTriggerState(triggerHashKey);
		}						
	} catch(Exception ex) {
		log.error("could not release acquired triggers", ex);
        throw new RuntimeException(ex.getMessage(), ex.getCause());
	} finally {
        lockPool.release();
	}		
}
 
Example 3
Source File: JobStoreSupport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void doUpdateOfMisfiredTrigger(Connection conn, OperableTrigger trig, boolean forceState, String newStateIfNotComplete, boolean recovering) throws JobPersistenceException {
    Calendar cal = null;
    if (trig.getCalendarName() != null) {
        cal = retrieveCalendar(conn, trig.getCalendarName());
    }

    schedSignaler.notifyTriggerListenersMisfired(trig);

    trig.updateAfterMisfire(cal);

    if (trig.getNextFireTime() == null) {
        storeTrigger(conn, trig,
            null, true, STATE_COMPLETE, forceState, recovering);
        schedSignaler.notifySchedulerListenersFinalized(trig);
    } else {
        storeTrigger(conn, trig, null, true, newStateIfNotComplete,
                forceState, false);
    }
}
 
Example 4
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 5
Source File: AbstractRedisStorage.java    From quartz-redis-jobstore with Apache License 2.0 5 votes vote down vote up
/**
 * Inform the <code>JobStore</code> that the scheduler no longer plans to
 * fire the given <code>Trigger</code>, that it had previously acquired
 * (reserved).
 * @param trigger the trigger to be released
 * @param jedis a thread-safe Redis connection
 */
public void releaseAcquiredTrigger(OperableTrigger trigger, T jedis) throws JobPersistenceException {
    final String triggerHashKey = redisSchema.triggerHashKey(trigger.getKey());
    if(jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.ACQUIRED), triggerHashKey) != null){
        if(trigger.getNextFireTime() != null){
            setTriggerState(RedisTriggerState.WAITING, (double) trigger.getNextFireTime().getTime(), triggerHashKey, jedis);
        }
        else{
            unsetTriggerState(triggerHashKey, jedis);
        }
    }
}
 
Example 6
Source File: AbstractRedisStorage.java    From quartz-redis-jobstore with Apache License 2.0 5 votes vote down vote up
/**
 * Determine whether or not the given trigger has misfired.
 * If so, notify the {@link org.quartz.spi.SchedulerSignaler} and update the trigger.
 * @param trigger the trigger to check for misfire
 * @param jedis a thread-safe Redis connection
 * @return false if the trigger has misfired; true otherwise
 * @throws JobPersistenceException
 */
protected boolean applyMisfire(OperableTrigger trigger, T jedis) throws JobPersistenceException {
    long misfireTime = System.currentTimeMillis();
    if(misfireThreshold > 0){
        misfireTime -= misfireThreshold;
    }
    final Date nextFireTime = trigger.getNextFireTime();
    if(nextFireTime == null || nextFireTime.getTime() > misfireTime
            || trigger.getMisfireInstruction() == Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY){
        return false;
    }

    Calendar calendar = null;
    if(trigger.getCalendarName() != null){
        calendar = retrieveCalendar(trigger.getCalendarName(), jedis);
    }
    signaler.notifyTriggerListenersMisfired((OperableTrigger) trigger.clone());

    trigger.updateAfterMisfire(calendar);

    storeTrigger(trigger, true, jedis);
    if(trigger.getNextFireTime() == null){
        setTriggerState(RedisTriggerState.COMPLETED, (double) System.currentTimeMillis(), redisSchema.triggerHashKey(trigger.getKey()), jedis);
        signaler.notifySchedulerListenersFinalized(trigger);
    }
    else if(nextFireTime.equals(trigger.getNextFireTime())){
        return false;
    }
    return true;
}
 
Example 7
Source File: RedisClusterStorage.java    From quartz-redis-jobstore with Apache License 2.0 5 votes vote down vote up
/**
 * Resume (un-pause) a {@link Trigger}
 *
 * @param triggerKey the key of the trigger to be resumed
 * @param jedis      a thread-safe Redis connection
 */
@Override
public void resumeTrigger(TriggerKey triggerKey, JedisClusterCommandsWrapper jedis) throws JobPersistenceException {
    final String triggerHashKey = redisSchema.triggerHashKey(triggerKey);
    Boolean exists = jedis.sismember(redisSchema.triggersSet(), triggerHashKey);
    Double isPaused = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.PAUSED), triggerHashKey);
    Double isPausedBlocked = jedis.zscore(redisSchema.triggerStateKey(RedisTriggerState.PAUSED_BLOCKED), triggerHashKey);

    if (!exists) {
        // Trigger does not exist.  Nothing to do.
        return;
    }
    if (isPaused == null && isPausedBlocked == null) {
        // Trigger is not paused. Nothing to do.
        return;
    }
    OperableTrigger trigger = retrieveTrigger(triggerKey, jedis);
    final String jobHashKey = redisSchema.jobHashKey(trigger.getJobKey());
    final Date nextFireTime = trigger.getNextFireTime();

    if (nextFireTime != null) {
        if (isBlockedJob(jobHashKey, jedis)) {
            setTriggerState(RedisTriggerState.BLOCKED, (double) nextFireTime.getTime(), triggerHashKey, jedis);
        } else {
            setTriggerState(RedisTriggerState.WAITING, (double) nextFireTime.getTime(), triggerHashKey, jedis);
        }
    }
    applyMisfire(trigger, jedis);
}
 
Example 8
Source File: JobStoreImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private boolean canBeAcquired(final TriggerEntity entity,
                              final ODatabaseDocumentTx db,
                              final long timeWindowStart,
                              final long timeWindowEnd)
{
  OperableTrigger trigger = entity.getValue();

  // skip triggers which have no next fire time
  if (trigger.getNextFireTime() == null) {
    return false;
  }

  // skip triggers which match misfire fudge logic (if the trigger will no longer fire)
  // NOTE: applyMisfire(...) may modify trigger.getNextFireTime()
  if (applyMisfire(db, entity) && trigger.getNextFireTime() == null) {
    return false;
  }

  // skip triggers which fire outside of requested window
  if (trigger.getNextFireTime().getTime() > timeWindowEnd) {
    return false;
  }

  // skip triggers which fire outside of requested window
  if (trigger.getMisfireInstruction() != Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY &&
      trigger.getNextFireTime().getTime() < timeWindowStart) {
    return false;
  }

  // check after misfire logic to avoid repeated log-spam
  if (isClustered() && isLimitedToMissingNode(entity)) {
    return false;
  }

  return true;
}
 
Example 9
Source File: JobStoreImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Determine if trigger has misfired.
 */
private boolean applyMisfire(final ODatabaseDocumentTx db, final TriggerEntity triggerEntity) {
  log.trace("Checking for misfire: {}", triggerEntity);

  OperableTrigger trigger = triggerEntity.getValue();

  long misfireTime = getMisfireTime();

  Date nextFireTime = trigger.getNextFireTime();
  if (nextFireTime == null || nextFireTime.getTime() > misfireTime ||
      trigger.getMisfireInstruction() == Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY) {
    return false;
  }

  // resolve trigger calender if there is one
  Calendar calendar = null;
  if (trigger.getCalendarName() != null) {
    calendar = findCalendar(db, trigger.getCalendarName());
  }

  signaler.notifyTriggerListenersMisfired(trigger);
  trigger.updateAfterMisfire(calendar);

  if (trigger.getNextFireTime() == null) {
    triggerEntity.setState(COMPLETE);
    triggerEntityAdapter.editEntity(db, triggerEntity);
    signaler.notifySchedulerListenersFinalized(trigger);
  }
  else if (nextFireTime.equals(trigger.getNextFireTime())) {
    return false;
  }

  return true;
}
 
Example 10
Source File: RedisJobStore.java    From redis-quartz with MIT License 5 votes vote down vote up
protected boolean applyMisfire(OperableTrigger trigger, Jedis jedis) throws JobPersistenceException {
   long misfireTime = System.currentTimeMillis();
   if (getMisfireThreshold() > 0)
       misfireTime -= getMisfireThreshold();       

   Date triggerNextFireTime = trigger.getNextFireTime();
   if (triggerNextFireTime == null || triggerNextFireTime.getTime() > misfireTime 
           || trigger.getMisfireInstruction() == Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY) { 
       return false; 
   }

   Calendar cal = null;
   if (trigger.getCalendarName() != null)
       cal = retrieveCalendar(trigger.getCalendarName(), jedis);       

   signaler.notifyTriggerListenersMisfired((OperableTrigger)trigger.clone());

   trigger.updateAfterMisfire(cal);
   
   if (triggerNextFireTime.equals(trigger.getNextFireTime()))
	   return false;

   storeTrigger(trigger, true, jedis);
   if (trigger.getNextFireTime() == null) { // Trigger completed
	   setTriggerState(RedisTriggerState.COMPLETED, (double)System.currentTimeMillis(), createTriggerHashKey(trigger.getKey().getGroup(), trigger.getKey().getName()));
	   signaler.notifySchedulerListenersFinalized(trigger);
   }
   
   return true;
}
 
Example 11
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 12
Source File: RedisStorage.java    From quartz-redis-jobstore with Apache License 2.0 5 votes vote down vote up
/**
 * Resume (un-pause) a {@link org.quartz.Trigger}
 * @param triggerKey the key of the trigger to be resumed
 * @param jedis a thread-safe Redis connection
 */
@Override
public void resumeTrigger(TriggerKey triggerKey, Jedis jedis) throws JobPersistenceException {
    final String triggerHashKey = redisSchema.triggerHashKey(triggerKey);
    Pipeline pipe = jedis.pipelined();
    Response<Boolean> exists = pipe.sismember(redisSchema.triggersSet(), triggerHashKey);
    Response<Double> isPaused = pipe.zscore(redisSchema.triggerStateKey(RedisTriggerState.PAUSED), triggerHashKey);
    Response<Double> isPausedBlocked = pipe.zscore(redisSchema.triggerStateKey(RedisTriggerState.PAUSED_BLOCKED), triggerHashKey);
    pipe.sync();

    if(!exists.get()){
        // Trigger does not exist.  Nothing to do.
        return;
    }
    if(isPaused.get() == null && isPausedBlocked.get() == null){
        // Trigger is not paused. Nothing to do.
        return;
    }
    OperableTrigger trigger = retrieveTrigger(triggerKey, jedis);
    final String jobHashKey = redisSchema.jobHashKey(trigger.getJobKey());
    final Date nextFireTime = trigger.getNextFireTime();

    if(nextFireTime != null){
        if(isBlockedJob(jobHashKey, jedis)){
            setTriggerState(RedisTriggerState.BLOCKED, (double) nextFireTime.getTime(), triggerHashKey, jedis);
        }
        else{
            setTriggerState(RedisTriggerState.WAITING, (double) nextFireTime.getTime(), triggerHashKey, jedis);
        }
    }
    applyMisfire(trigger, jedis);
}
 
Example 13
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 14
Source File: RedisJobStore.java    From redis-quartz with MIT License 4 votes vote down vote up
@Override
public List<OperableTrigger> acquireNextTriggers(long noLaterThan,
		int maxCount, long timeWindow) throws JobPersistenceException {

	// Run job store background functionality periodically in acquireNextTriggers since we know this is called periodically by the scheduler  
	keepAlive();
	releaseTriggersCron();
	
     List<OperableTrigger> acquiredTriggers = new ArrayList<>();
     try (Jedis jedis = pool.getResource()) {
        lockPool.acquire();
		boolean retry = true;
		while (retry) {
			retry = false;
           Set<String> acquiredJobHashKeysForNoConcurrentExec = new HashSet<>();
			Set<Tuple> triggerTuples = jedis.zrangeByScoreWithScores(RedisTriggerState.WAITING.getKey(), 0d, (double)(noLaterThan + timeWindow), 0, maxCount);
			for (Tuple triggerTuple : triggerTuples) {
				OperableTrigger trigger = retrieveTrigger(new TriggerKey(triggerTuple.getElement().split(":")[2], triggerTuple.getElement().split(":")[1]), jedis);
								
				// handling misfires
				if (applyMisfire(trigger, jedis)) {
					log.debug("misfired trigger: " + triggerTuple.getElement());
					retry = true;
					break;
				}				
					
				// if the trigger has no next fire time its WAITING state should be unset 
				if (trigger.getNextFireTime() == null) {
					unsetTriggerState(triggerTuple.getElement());
					continue;
				}
				
				// if the trigger's job is annotated as @DisallowConcurrentExecution, check if one of its triggers were already acquired
				String jobHashKey = createJobHashKey(trigger.getJobKey().getGroup(), trigger.getJobKey().getName());
				if (isJobConcurrentExectionDisallowed(jedis.hget(jobHashKey, JOB_CLASS))) {
					if (acquiredJobHashKeysForNoConcurrentExec.contains(jobHashKey)) // a trigger is already acquired for this job, continue to the next trigger
						continue;
					else
						acquiredJobHashKeysForNoConcurrentExec.add(jobHashKey);
				}
				
				// acquiring trigger
				jedis.hset(triggerTuple.getElement(), LOCKED_BY, instanceId);
				jedis.hset(triggerTuple.getElement(), LOCK_TIME, Long.toString(System.currentTimeMillis()));
				setTriggerState(RedisTriggerState.ACQUIRED, triggerTuple.getScore(), triggerTuple.getElement());
				acquiredTriggers.add(trigger);
				log.debug("trigger: " + triggerTuple.getElement() + " acquired");												
			}
		}
	} catch(Exception ex) {
		log.error("could not acquire next triggers", ex);
		throw new JobPersistenceException(ex.getMessage(), ex.getCause());
	} finally {
        lockPool.release();
	}
	return acquiredTriggers;
}
 
Example 15
Source File: RedisStorage.java    From quartz-redis-jobstore with Apache License 2.0 4 votes vote down vote up
/**
 * Store a trigger in redis
 * @param trigger the trigger to be stored
 * @param replaceExisting true if an existing trigger with the same identity should be replaced
 * @param jedis a thread-safe Redis connection
 * @throws JobPersistenceException
 * @throws ObjectAlreadyExistsException
 */
@Override
public void storeTrigger(OperableTrigger trigger, boolean replaceExisting, Jedis jedis) throws JobPersistenceException {
    final String triggerHashKey = redisSchema.triggerHashKey(trigger.getKey());
    final String triggerGroupSetKey = redisSchema.triggerGroupSetKey(trigger.getKey());
    final String jobTriggerSetKey = redisSchema.jobTriggersSetKey(trigger.getJobKey());

    if(!(trigger instanceof SimpleTrigger) && !(trigger instanceof CronTrigger)){
        throw new UnsupportedOperationException("Only SimpleTrigger and CronTrigger are supported.");
    }
    final boolean exists = jedis.exists(triggerHashKey);
    if(exists && !replaceExisting){
        throw new ObjectAlreadyExistsException(trigger);
    }

    Map<String, String> triggerMap = mapper.convertValue(trigger, new TypeReference<HashMap<String, String>>() {});
    triggerMap.put(TRIGGER_CLASS, trigger.getClass().getName());

    Pipeline pipe = jedis.pipelined();
    pipe.hmset(triggerHashKey, triggerMap);
    pipe.sadd(redisSchema.triggersSet(), triggerHashKey);
    pipe.sadd(redisSchema.triggerGroupsSet(), triggerGroupSetKey);
    pipe.sadd(triggerGroupSetKey, triggerHashKey);
    pipe.sadd(jobTriggerSetKey, triggerHashKey);
    if(trigger.getCalendarName() != null && !trigger.getCalendarName().isEmpty()){
        final String calendarTriggersSetKey = redisSchema.calendarTriggersSetKey(trigger.getCalendarName());
        pipe.sadd(calendarTriggersSetKey, triggerHashKey);
    }
    if (trigger.getJobDataMap() != null && !trigger.getJobDataMap().isEmpty()) {
        final String triggerDataMapHashKey = redisSchema.triggerDataMapHashKey(trigger.getKey());
        pipe.hmset(triggerDataMapHashKey, getStringDataMap(trigger.getJobDataMap()));
    }
    pipe.sync();

    if(exists){
        // We're overwriting a previously stored instance of this trigger, so clear any existing trigger state.
        unsetTriggerState(triggerHashKey, jedis);
    }

    pipe = jedis.pipelined();
    Response<Boolean> triggerPausedResponse = pipe.sismember(redisSchema.pausedTriggerGroupsSet(), triggerGroupSetKey);
    Response<Boolean> jobPausedResponse = pipe.sismember(redisSchema.pausedJobGroupsSet(), redisSchema.jobGroupSetKey(trigger.getJobKey()));
    pipe.sync();
    final String jobHashKey = redisSchema.jobHashKey(trigger.getJobKey());
    final long nextFireTime = trigger.getNextFireTime() != null ? trigger.getNextFireTime().getTime() : -1;
    if (triggerPausedResponse.get() || jobPausedResponse.get()){
        if (isBlockedJob(jobHashKey, jedis)) {
            setTriggerState(RedisTriggerState.PAUSED_BLOCKED, (double) nextFireTime, triggerHashKey, jedis);
        } else {
            setTriggerState(RedisTriggerState.PAUSED, (double) nextFireTime, triggerHashKey, jedis);
        }
    } else if(trigger.getNextFireTime() != null){
        if (isBlockedJob(jobHashKey, jedis)) {
            setTriggerState(RedisTriggerState.BLOCKED, nextFireTime, triggerHashKey, jedis);
        } else {
            setTriggerState(RedisTriggerState.WAITING, (double) trigger.getNextFireTime().getTime(), triggerHashKey, jedis);
        }
    }
}
 
Example 16
Source File: RedisClusterStorage.java    From quartz-redis-jobstore with Apache License 2.0 4 votes vote down vote up
/**
 * Store a trigger in redis
 *
 * @param trigger         the trigger to be stored
 * @param replaceExisting true if an existing trigger with the same identity should be replaced
 * @param jedis           a thread-safe Redis connection
 * @throws JobPersistenceException
 * @throws ObjectAlreadyExistsException
 */
@Override
public void storeTrigger(OperableTrigger trigger, boolean replaceExisting, JedisClusterCommandsWrapper jedis) throws JobPersistenceException {
    final String triggerHashKey = redisSchema.triggerHashKey(trigger.getKey());
    final String triggerGroupSetKey = redisSchema.triggerGroupSetKey(trigger.getKey());
    final String jobTriggerSetKey = redisSchema.jobTriggersSetKey(trigger.getJobKey());

    if (!(trigger instanceof SimpleTrigger) && !(trigger instanceof CronTrigger)) {
        throw new UnsupportedOperationException("Only SimpleTrigger and CronTrigger are supported.");
    }
    final boolean exists = jedis.exists(triggerHashKey);
    if (exists && !replaceExisting) {
        throw new ObjectAlreadyExistsException(trigger);
    }

    Map<String, String> triggerMap = mapper.convertValue(trigger, new TypeReference<HashMap<String, String>>() {
    });
    triggerMap.put(TRIGGER_CLASS, trigger.getClass().getName());

    jedis.hmset(triggerHashKey, triggerMap);
    jedis.sadd(redisSchema.triggersSet(), triggerHashKey);
    jedis.sadd(redisSchema.triggerGroupsSet(), triggerGroupSetKey);
    jedis.sadd(triggerGroupSetKey, triggerHashKey);
    jedis.sadd(jobTriggerSetKey, triggerHashKey);
    if (trigger.getCalendarName() != null && !trigger.getCalendarName().isEmpty()) {
        final String calendarTriggersSetKey = redisSchema.calendarTriggersSetKey(trigger.getCalendarName());
        jedis.sadd(calendarTriggersSetKey, triggerHashKey);
    }
    if (trigger.getJobDataMap() != null && !trigger.getJobDataMap().isEmpty()) {
        final String triggerDataMapHashKey = redisSchema.triggerDataMapHashKey(trigger.getKey());
        jedis.hmset(triggerDataMapHashKey, getStringDataMap(trigger.getJobDataMap()));
    }

    if (exists) {
        // We're overwriting a previously stored instance of this trigger, so clear any existing trigger state.
        unsetTriggerState(triggerHashKey, jedis);
    }

    Boolean triggerPausedResponse = jedis.sismember(redisSchema.pausedTriggerGroupsSet(), triggerGroupSetKey);
    Boolean jobPausedResponse = jedis.sismember(redisSchema.pausedJobGroupsSet(), redisSchema.jobGroupSetKey(trigger.getJobKey()));

    if (triggerPausedResponse || jobPausedResponse) {
        final long nextFireTime = trigger.getNextFireTime() != null ? trigger.getNextFireTime().getTime() : -1;
        final String jobHashKey = redisSchema.jobHashKey(trigger.getJobKey());
        if (isBlockedJob(jobHashKey, jedis)) {
            setTriggerState(RedisTriggerState.PAUSED_BLOCKED, (double) nextFireTime, triggerHashKey, jedis);
        } else {
            setTriggerState(RedisTriggerState.PAUSED, (double) nextFireTime, triggerHashKey, jedis);
        }
    } else if (trigger.getNextFireTime() != null) {
        setTriggerState(RedisTriggerState.WAITING, (double) trigger.getNextFireTime().getTime(), triggerHashKey, jedis);
    }
}
 
Example 17
Source File: OracleDelegate.java    From fixflow with Apache License 2.0 4 votes vote down vote up
@Override
public int updateTrigger(Connection conn, OperableTrigger trigger, String state,
        JobDetail jobDetail) throws SQLException, IOException {

    // save some clock cycles by unnecessarily writing job data blob ...
    boolean updateJobData = trigger.getJobDataMap().isDirty();
    byte[] data = null;
    if (updateJobData && trigger.getJobDataMap().size() > 0) {
        data = serializeJobData(trigger.getJobDataMap()).toByteArray();
    }
            
    PreparedStatement ps = null;
    PreparedStatement ps2 = null;
    ResultSet rs = null;
    
    int insertResult = 0;


    try {
        ps = conn.prepareStatement(rtp(UPDATE_ORACLE_TRIGGER));
            
        ps.setString(1, trigger.getJobKey().getName());
        ps.setString(2, trigger.getJobKey().getGroup());
        ps.setString(3, trigger.getDescription());
        long nextFireTime = -1;
        if (trigger.getNextFireTime() != null) {
            nextFireTime = trigger.getNextFireTime().getTime();
        }
        ps.setBigDecimal(4, new BigDecimal(String.valueOf(nextFireTime)));
        long prevFireTime = -1;
        if (trigger.getPreviousFireTime() != null) {
            prevFireTime = trigger.getPreviousFireTime().getTime();
        }
        ps.setBigDecimal(5, new BigDecimal(String.valueOf(prevFireTime)));
        ps.setString(6, state);
        
        TriggerPersistenceDelegate tDel = findTriggerPersistenceDelegate(trigger);
        
        String type = TTYPE_BLOB;
        if(tDel != null)
            type = tDel.getHandledTriggerTypeDiscriminator();

        ps.setString(7, type);
        
        ps.setBigDecimal(8, new BigDecimal(String.valueOf(trigger
                .getStartTime().getTime())));
        long endTime = 0;
        if (trigger.getEndTime() != null) {
            endTime = trigger.getEndTime().getTime();
        }
        ps.setBigDecimal(9, new BigDecimal(String.valueOf(endTime)));
        ps.setString(10, trigger.getCalendarName());
        ps.setInt(11, trigger.getMisfireInstruction());
        ps.setInt(12, trigger.getPriority());
        ps.setString(13, trigger.getKey().getName());
        ps.setString(14, trigger.getKey().getGroup());

        insertResult = ps.executeUpdate();

        if(updateJobData) {
            ps.close();

            ps = conn
                    .prepareStatement(rtp(UPDATE_ORACLE_TRIGGER_JOB_DETAIL_EMPTY_BLOB));
            ps.setString(1, trigger.getKey().getName());
            ps.setString(2, trigger.getKey().getGroup());
            ps.executeUpdate();
            ps.close();

            ps = conn.prepareStatement(rtp(SELECT_ORACLE_TRIGGER_JOB_DETAIL_BLOB));
            ps.setString(1, trigger.getKey().getName());
            ps.setString(2, trigger.getKey().getGroup());

            rs = ps.executeQuery();

            if (rs.next()) {
                //Blob dbBlob = writeDataToBlob(rs, 1, data);
                ps2 = conn.prepareStatement(rtp(UPDATE_ORACLE_TRIGGER_JOB_DETAIL_BLOB));

                ps2.setObject(1, data);
                ps2.setString(2, trigger.getKey().getName());
                ps2.setString(3, trigger.getKey().getGroup());

                ps2.executeUpdate();
            }
        }
        
        if(tDel == null)
            updateBlobTrigger(conn, trigger);
        else
            tDel.updateExtendedTriggerProperties(conn, trigger, state, jobDetail);

    } finally {
        closeResultSet(rs);
        closeStatement(ps);
        closeStatement(ps2);
    }

    return insertResult;
}
 
Example 18
Source File: OracleDelegate.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public int updateTrigger(Connection conn, OperableTrigger trigger, String state,
        JobDetail jobDetail) throws SQLException, IOException {

    // save some clock cycles by unnecessarily writing job data blob ...
    boolean updateJobData = trigger.getJobDataMap().isDirty();
    byte[] data = null;
    if (updateJobData && trigger.getJobDataMap().size() > 0) {
        data = serializeJobData(trigger.getJobDataMap()).toByteArray();
    }
            
    PreparedStatement ps = null;
    PreparedStatement ps2 = null;
    ResultSet rs = null;
    
    int insertResult = 0;


    try {
        ps = conn.prepareStatement(rtp(UPDATE_ORACLE_TRIGGER));
            
        ps.setString(1, trigger.getJobKey().getName());
        ps.setString(2, trigger.getJobKey().getGroup());
        ps.setString(3, trigger.getDescription());
        long nextFireTime = -1;
        if (trigger.getNextFireTime() != null) {
            nextFireTime = trigger.getNextFireTime().getTime();
        }
        ps.setBigDecimal(4, new BigDecimal(String.valueOf(nextFireTime)));
        long prevFireTime = -1;
        if (trigger.getPreviousFireTime() != null) {
            prevFireTime = trigger.getPreviousFireTime().getTime();
        }
        ps.setBigDecimal(5, new BigDecimal(String.valueOf(prevFireTime)));
        ps.setString(6, state);
        
        TriggerPersistenceDelegate tDel = findTriggerPersistenceDelegate(trigger);
        
        String type = TTYPE_BLOB;
        if(tDel != null)
            type = tDel.getHandledTriggerTypeDiscriminator();

        ps.setString(7, type);
        
        ps.setBigDecimal(8, new BigDecimal(String.valueOf(trigger
                .getStartTime().getTime())));
        long endTime = 0;
        if (trigger.getEndTime() != null) {
            endTime = trigger.getEndTime().getTime();
        }
        ps.setBigDecimal(9, new BigDecimal(String.valueOf(endTime)));
        ps.setString(10, trigger.getCalendarName());
        ps.setInt(11, trigger.getMisfireInstruction());
        ps.setInt(12, trigger.getPriority());
        ps.setString(13, trigger.getKey().getName());
        ps.setString(14, trigger.getKey().getGroup());

        insertResult = ps.executeUpdate();

        if(updateJobData) {
            ps.close();

            ps = conn
                    .prepareStatement(rtp(UPDATE_ORACLE_TRIGGER_JOB_DETAIL_EMPTY_BLOB));
            ps.setString(1, trigger.getKey().getName());
            ps.setString(2, trigger.getKey().getGroup());
            ps.executeUpdate();
            ps.close();

            ps = conn.prepareStatement(rtp(SELECT_ORACLE_TRIGGER_JOB_DETAIL_BLOB));
            ps.setString(1, trigger.getKey().getName());
            ps.setString(2, trigger.getKey().getGroup());

            rs = ps.executeQuery();

            if (rs.next()) {
                Blob dbBlob = writeDataToBlob(rs, 1, data);
                ps2 = conn.prepareStatement(rtp(UPDATE_ORACLE_TRIGGER_JOB_DETAIL_BLOB));

                ps2.setBlob(1, dbBlob);
                ps2.setString(2, trigger.getKey().getName());
                ps2.setString(3, trigger.getKey().getGroup());

                ps2.executeUpdate();
            }
        }
        
        if(tDel == null)
            updateBlobTrigger(conn, trigger);
        else
            tDel.updateExtendedTriggerProperties(conn, trigger, state, jobDetail);

    } finally {
        closeResultSet(rs);
        closeStatement(ps);
        closeStatement(ps2);
    }

    return insertResult;
}
 
Example 19
Source File: AbstractRedisStorage.java    From quartz-redis-jobstore with Apache License 2.0 4 votes vote down vote up
/**
 * Get a handle to the next trigger to be fired, and mark it as 'reserved'
 * by the calling scheduler.
 *
 * @param noLaterThan If > 0, the JobStore should only return a Trigger
 *                    that will fire no later than the time represented in this value as
 *                    milliseconds.
 * @param maxCount  the maximum number of triggers to return
 * @param timeWindow    the time window within which the triggers must fire next
 * @param jedis a thread-safe Redis connection
 * @return the acquired triggers
 * @throws JobPersistenceException
 */
public List<OperableTrigger> acquireNextTriggers(long noLaterThan, int maxCount, long timeWindow, T jedis) throws JobPersistenceException, ClassNotFoundException {
    releaseTriggersCron(jedis);
    setLastInstanceActiveTime(schedulerInstanceId, System.currentTimeMillis(), jedis);
    List<OperableTrigger> acquiredTriggers = new ArrayList<>();
    boolean retry;
    do{
        retry = false;
        Set<String> acquiredJobHashKeysForNoConcurrentExec = new HashSet<>();
        if (logger.isTraceEnabled()) {
            logger.trace("Current time is {}. Attempting to acquire triggers firing no later than {}", System.currentTimeMillis(), (noLaterThan + timeWindow));
        }
        for (Tuple triggerTuple : jedis.zrangeByScoreWithScores(redisSchema.triggerStateKey(RedisTriggerState.WAITING), 0, (double) (noLaterThan + timeWindow), 0, maxCount)) {
            OperableTrigger trigger = retrieveTrigger(redisSchema.triggerKey(triggerTuple.getElement()), jedis);
            if(applyMisfire(trigger, jedis)){
                if (logger.isDebugEnabled()) {
                    logger.debug("misfired trigger: " + triggerTuple.getElement());
                }
                retry = true;
                break;
            }
            if(trigger.getNextFireTime() == null){
                // Trigger has no next fire time. Unset its WAITING state.
                unsetTriggerState(triggerTuple.getElement(), jedis);
                continue;
            }
            final String jobHashKey = redisSchema.jobHashKey(trigger.getJobKey());
            JobDetail job = retrieveJob(trigger.getJobKey(), jedis);
            if(job != null && isJobConcurrentExecutionDisallowed(job.getJobClass())){
                if (logger.isTraceEnabled()) {
                    logger.trace("Attempting to acquire job " + job.getKey() + " with concurrent execution disallowed.");
                }
                if (acquiredJobHashKeysForNoConcurrentExec.contains(jobHashKey)) {
                    // a trigger is already acquired for this job
                    if (logger.isTraceEnabled()) {
                        logger.trace("Job " + job.getKey() + " with concurrent execution disallowed already acquired.");
                    }
                    continue;
                } else {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Job " + job.getKey() + " with concurrent execution disallowed not yet acquired. Acquiring.");
                    }
                    acquiredJobHashKeysForNoConcurrentExec.add(jobHashKey);
                }
            }
            // acquire the trigger
            setTriggerState(RedisTriggerState.ACQUIRED, triggerTuple.getScore(), triggerTuple.getElement(), jedis);
            if (job != null && isJobConcurrentExecutionDisallowed(job.getJobClass())) {
                // setting the trigger state above will have removed any lock which was present, so we need to lock the trigger, again
                lockTrigger(trigger.getKey(), jedis);
            }
            acquiredTriggers.add(trigger);
            logger.debug(String.format("Trigger %s acquired", triggerTuple.getElement()));
        }
    }while (retry);
    return acquiredTriggers;
}
 
Example 20
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;
    }
}