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

The following examples show how to use org.quartz.spi.OperableTrigger#triggered() . 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: 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 3
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 4
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 5
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 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: 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;		
}