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

The following examples show how to use org.quartz.spi.OperableTrigger#getCalendarName() . 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: RAMJobStore.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>
 * Remove (delete) the <code>{@link org.quartz.Calendar}</code> with the
 * given name.
 * </p>
 *
 * <p>
 * If removal of the <code>Calendar</code> would result in
 * <code>Trigger</code>s pointing to non-existent calendars, then a
 * <code>JobPersistenceException</code> will be thrown.</p>
 *       *
 * @param calName The name of the <code>Calendar</code> to be removed.
 * @return <code>true</code> if a <code>Calendar</code> with the given name
 * was found and removed from the store.
 */
public boolean removeCalendar(String calName)
    throws JobPersistenceException {
    int numRefs = 0;

    synchronized (lock) {
        for (TriggerWrapper trigger : triggers) {
            OperableTrigger trigg = trigger.trigger;
            if (trigg.getCalendarName() != null
                    && trigg.getCalendarName().equals(calName)) {
                numRefs++;
            }
        }
    }

    if (numRefs > 0) {
        throw new JobPersistenceException(
                "Calender cannot be removed if it referenced by a Trigger!");
    }

    return (calendarsByName.remove(calName) != null);
}
 
Example 2
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 3
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 4
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 5
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 6
Source File: JobStoreImpl.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Processes a fired trigger, if the trigger (and related entities) still exist and the trigger is in proper state.
 */
@Nullable
private TriggerFiredBundle triggerFired(final ODatabaseDocumentTx db, final OperableTrigger firedTrigger) {
  log.debug("Trigger fired: {}", firedTrigger);

  // resolve the entity for fired trigger
  final TriggerKey triggerKey = firedTrigger.getKey();
  TriggerEntity entity = triggerEntityAdapter.readByKey(db, triggerKey);

  // skip if trigger was deleted
  if (entity == null) {
    log.trace("Trigger deleted; skipping");
    return null;
  }

  // skip if trigger is not in ACQUIRED state
  if (entity.getState() != ACQUIRED) {
    log.trace("Trigger state != ACQUIRED; skipping");
    return null;
  }

  OperableTrigger trigger = entity.getValue();

  // resolve trigger calender if there is one
  Calendar calendar = null;
  if (trigger.getCalendarName() != null) {
    calendar = findCalendar(db, trigger.getCalendarName());
    if (calendar == null) {
      log.trace("Calender was deleted; skipping");
      return null;
    }
  }

  Date prevFireTime = trigger.getPreviousFireTime();

  // inform both scheduler and persistent instances were triggered
  firedTrigger.triggered(calendar);
  trigger.triggered(calendar);

  // update trigger to WAITING state
  entity.setState(WAITING);
  triggerEntityAdapter.editEntity(db, entity);

  // re-resolve trigger value after edit for sanity
  trigger = entity.getValue();

  // resolve the job-detail for this trigger
  JobDetailEntity jobDetailEntity = jobDetailEntityAdapter.readByKey(db, trigger.getJobKey());
  checkState(jobDetailEntity != null, "Missing job-detail for trigger-key: %s", triggerKey);
  JobDetail jobDetail = jobDetailEntity.getValue();

  // block triggers for job if concurrent execution is disallowed
  if (jobDetail.isConcurrentExectionDisallowed()) {
    blockTriggers(db, triggerKey, jobDetail);
  }

  jobDetail.getJobDataMap().clearDirtyFlag(); // clear before handing to quartz

  return new TriggerFiredBundle(
      jobDetail,
      trigger,
      calendar,
      false,
      new Date(),
      trigger.getPreviousFireTime(),
      prevFireTime,
      trigger.getNextFireTime()
  );
}
 
Example 7
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 8
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 9
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 10
Source File: RedisJobStore.java    From redis-quartz with MIT License 4 votes vote down vote up
/**
 * Stores trigger in redis.
 *
 * @param newTrigger the new trigger
 * @param replaceExisting replace existing
 * @param jedis thread-safe redis connection
 * @throws JobPersistenceException
 * @throws ObjectAlreadyExistsException
 */
private void storeTrigger(OperableTrigger newTrigger, boolean replaceExisting, Jedis jedis)
          throws JobPersistenceException {
	String triggerHashKey = createTriggerHashKey(newTrigger.getKey().getGroup(), newTrigger.getKey().getName());
	String triggerGroupSetKey = createTriggerGroupSetKey(newTrigger.getKey().getGroup());
	String jobHashkey = createJobHashKey(newTrigger.getJobKey().getGroup(), newTrigger.getJobKey().getName());
	String jobTriggerSetkey = createJobTriggersSetKey(newTrigger.getJobKey().getGroup(), newTrigger.getJobKey().getName());
	
     if (jedis.exists(triggerHashKey) && !replaceExisting) {
        ObjectAlreadyExistsException ex = new ObjectAlreadyExistsException(newTrigger);
        log.warn(ex.toString());
     }
     Map<String, String> trigger = new HashMap<>();
	trigger.put(JOB_HASH_KEY, jobHashkey);
	trigger.put(DESCRIPTION, newTrigger.getDescription() != null ? newTrigger.getDescription() : "");
	trigger.put(NEXT_FIRE_TIME, newTrigger.getNextFireTime() != null ? Long.toString(newTrigger.getNextFireTime().getTime()) : "");
	trigger.put(PREV_FIRE_TIME, newTrigger.getPreviousFireTime() != null ? Long.toString(newTrigger.getPreviousFireTime().getTime()) : "");
	trigger.put(PRIORITY, Integer.toString(newTrigger.getPriority()));
	trigger.put(START_TIME, newTrigger.getStartTime() != null ? Long.toString(newTrigger.getStartTime().getTime()) : "");
	trigger.put(END_TIME, newTrigger.getEndTime() != null ? Long.toString(newTrigger.getEndTime().getTime()) : "");
	trigger.put(FINAL_FIRE_TIME, newTrigger.getFinalFireTime() != null ? Long.toString(newTrigger.getFinalFireTime().getTime()) : "");
	trigger.put(FIRE_INSTANCE_ID, newTrigger.getFireInstanceId() != null ?  newTrigger.getFireInstanceId() : "");
	trigger.put(MISFIRE_INSTRUCTION, Integer.toString(newTrigger.getMisfireInstruction()));
	trigger.put(CALENDAR_NAME, newTrigger.getCalendarName() != null ? newTrigger.getCalendarName() : "");
	if (newTrigger instanceof SimpleTrigger) {
		trigger.put(TRIGGER_TYPE, TRIGGER_TYPE_SIMPLE);
		trigger.put(REPEAT_COUNT, Integer.toString(((SimpleTrigger) newTrigger).getRepeatCount()));
		trigger.put(REPEAT_INTERVAL, Long.toString(((SimpleTrigger) newTrigger).getRepeatInterval()));
		trigger.put(TIMES_TRIGGERED, Integer.toString(((SimpleTrigger) newTrigger).getTimesTriggered()));
	} else if (newTrigger instanceof CronTrigger) {
		trigger.put(TRIGGER_TYPE, TRIGGER_TYPE_CRON);
		trigger.put(CRON_EXPRESSION, ((CronTrigger) newTrigger).getCronExpression() != null ? ((CronTrigger) newTrigger).getCronExpression() : "");
		trigger.put(TIME_ZONE_ID, ((CronTrigger) newTrigger).getTimeZone().getID() != null ? ((CronTrigger) newTrigger).getTimeZone().getID() : "");
	} else { // other trigger types are not supported
		 throw new UnsupportedOperationException();
	}		
	
	jedis.hmset(triggerHashKey, trigger);
	jedis.sadd(TRIGGERS_SET, triggerHashKey);
	jedis.sadd(TRIGGER_GROUPS_SET, triggerGroupSetKey);			
	jedis.sadd(triggerGroupSetKey, triggerHashKey);
	jedis.sadd(jobTriggerSetkey, triggerHashKey);
	if (newTrigger.getCalendarName() != null && !newTrigger.getCalendarName().isEmpty()) { // storing the trigger for calendar, if exists
		String calendarTriggersSetKey = createCalendarTriggersSetKey(newTrigger.getCalendarName());
		jedis.sadd(calendarTriggersSetKey, triggerHashKey);
	}
	
	if (jedis.sismember(PAUSED_TRIGGER_GROUPS_SET, triggerGroupSetKey) || jedis.sismember(PAUSED_JOB_GROUPS_SET, createJobGroupSetKey(newTrigger.getJobKey().getGroup()))) {	
		long nextFireTime = newTrigger.getNextFireTime() != null ? newTrigger.getNextFireTime().getTime() : -1;
		if (jedis.sismember(BLOCKED_JOBS_SET, jobHashkey))
			setTriggerState(RedisTriggerState.PAUSED_BLOCKED, (double)nextFireTime, triggerHashKey);
		else
			setTriggerState(RedisTriggerState.PAUSED, (double)nextFireTime, triggerHashKey);
	} else if (newTrigger.getNextFireTime() != null) {			
		setTriggerState(RedisTriggerState.WAITING, (double)newTrigger.getNextFireTime().getTime(), triggerHashKey);
	}
}
 
Example 11
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;		
}