/** * Marks and returns the next trigger to execute, preferring the given custId. If no appropriate * trigger can be found for the given customerId, a trigger may be returned belonging to a * different custId. (Paused triggers will be ignored by this method.) */ private Trigger acquireNextTrigger(SchedulingContext ctxt, long custId) { WrappedTrigger nonCustomerMatch = null; for (Iterator<WrappedTrigger> it = m_triggersByScore.iterator(); it.hasNext(); ) { WrappedTrigger wt = it.next(); // compare customer first if we already have a non-customer match if ((custId > 0) && (custId != wt.getCustomerId()) && (nonCustomerMatch != null)) { continue; } if (wt.getState() != Trigger.STATE_NORMAL) { continue; } Trigger t = wt.getTrigger(); if (!isEligibleGroupName(t.getGroup())) { continue; } if ((custId > 0) && (custId != wt.getCustomerId())) { nonCustomerMatch = wt; } else { // s_logCategory.debug("acquireNextTrigger(" + custId + ") returning trigger for " + // wt.getCustomerId()); return claimTrigger(wt); } } if (nonCustomerMatch == null) { return null; } else { // s_logCategory.debug("acquireNextTrigger(" + custId + ") returning trigger for " + // nonCustomerMatch.getCustomerId()); return claimTrigger(nonCustomerMatch); } }
protected void update( Scheduler scheduler, com.liferay.portal.kernel.scheduler.Trigger trigger, StorageType storageType) throws Exception { Trigger quartzTrigger = getQuartzTrigger(trigger, storageType); if (quartzTrigger == null) { return; } TriggerKey triggerKey = quartzTrigger.getKey(); if (scheduler.getTrigger(triggerKey) != null) { scheduler.rescheduleJob(triggerKey, quartzTrigger); } else { JobKey jobKey = quartzTrigger.getJobKey(); JobDetail jobDetail = scheduler.getJobDetail(jobKey); if (jobDetail == null) { return; } synchronized (this) { scheduler.deleteJob(jobKey); scheduler.scheduleJob(jobDetail, quartzTrigger); } updateJobState(scheduler, jobKey, TriggerState.NORMAL, true); } }
/** * Add the given trigger to the Scheduler, if it doesn't already exist. Overwrites the trigger in * any case if "overwriteExistingJobs" is set. * * @param trigger the trigger to add * @return {@code true} if the trigger was actually added, {@code false} if it already existed * before * @see #setOverwriteExistingJobs */ private boolean addTriggerToScheduler(Trigger trigger) throws SchedulerException { boolean triggerExists = (getScheduler().getTrigger(trigger.getKey()) != null); if (!triggerExists || this.overwriteExistingJobs) { // Check if the Trigger is aware of an associated JobDetail. JobDetail jobDetail = (JobDetail) trigger.getJobDataMap().remove("jobDetail"); if (jobDetail != null) { // Automatically register the JobDetail too. if (!this.jobDetails.contains(jobDetail) && addJobToScheduler(jobDetail)) { this.jobDetails.add(jobDetail); } } if (!triggerExists) { try { getScheduler().scheduleJob(trigger); } catch (ObjectAlreadyExistsException ex) { if (logger.isDebugEnabled()) { logger.debug( "Unexpectedly found existing trigger, assumably due to cluster race condition: " + ex.getMessage() + " - can safely be ignored"); } if (this.overwriteExistingJobs) { getScheduler().rescheduleJob(trigger.getKey(), trigger); } } } else { getScheduler().rescheduleJob(trigger.getKey(), trigger); } return true; } else { return false; } }
@SuppressWarnings("unchecked") public void runAllTasks() throws TaskSystemException { try { List<String> triggerNames; List<Trigger> triggers = new ArrayList<Trigger>(); String[] groupNames = scheduler.getTriggerGroupNames(); for (String group : groupNames) { triggerNames = new ArrayList<String>(Arrays.asList(scheduler.getTriggerNames(group))); for (String triggerName : triggerNames) { triggers.add(scheduler.getTrigger(triggerName, group)); } } Collections.sort( triggers, new Comparator<Trigger>() { @Override public int compare(Trigger trigger1, Trigger trigger2) { if (trigger1.getPriority() < trigger2.getPriority()) { return -1; } else if (trigger1.getPriority() > trigger2.getPriority()) { return 1; } else { return 0; } } }); for (Trigger trigger : triggers) { scheduler.triggerJob(trigger.getJobName(), trigger.getJobGroup()); } } catch (SchedulerException se) { throw new TaskSystemException(se); } }
@Override public void triggerJob(String jobId) { try { List<? extends Trigger> existingTriggers = sched.getTriggersOfJob(jobKey(jobId, Scheduler.DEFAULT_GROUP)); if (!existingTriggers.isEmpty()) { // Note: we assume that every job has exactly one trigger Trigger oldTrigger = existingTriggers.get(0); TriggerKey oldTriggerKey = oldTrigger.getKey(); Trigger newTrigger = newTrigger() .withIdentity(oldTriggerKey) .startAt(getFutureDate(0, TimeUnit.MILLISECONDS)) .build(); rescheduleAJob(oldTriggerKey.getName(), oldTriggerKey.getGroup(), newTrigger); } else { log.error("failed to trigger a job with id={}, job has no trigger", jobId); } } catch (SchedulerException se) { log.error("failed to trigger a job with id={}: {}", jobId, se.getMessage()); log.debug("Exception", se); } }
private long getCustomerId(SchedulingContext ctxt, Trigger t) throws JobPersistenceException { JobDetail jd = retrieveJob(ctxt, t.getJobName(), t.getJobGroup()); if (jd == null) { return -1L; } JobDataMap jdMap = jd.getJobDataMap(); return jdMap.getLong("customerId"); }
private List<DateTime> getFireTimes(String key) throws SchedulerException { Trigger trigger = scheduler.getTrigger(triggerKey(key, "default")); List<DateTime> fireTimes = new ArrayList<>(); Date nextFireTime = trigger.getNextFireTime(); while (nextFireTime != null) { fireTimes.add(newDateTime(nextFireTime)); nextFireTime = trigger.getFireTimeAfter(nextFireTime); } return fireTimes; }
protected boolean triggerExists(Trigger checkTrigger) { try { Trigger trigger = resourceScheduler.getTrigger(checkTrigger.getName(), checkTrigger.getGroup()); return (trigger != null); } catch (SchedulerException e) { log.error("Failed to check if the trigger exists", e); } return false; }
/** * Resume (un-pause) the <code>{@link org.quartz.Job}</code> with the given name. * * <p>If any of the <code>Job</code>'s<code>Trigger</code> s missed one or more fire-times, then * the <code>Trigger</code>'s misfire instruction will be applied. * * @see #pauseJob(org.quartz.core.SchedulingContext, String, String) */ public void resumeJob(SchedulingContext ctxt, String jobName, String groupName) throws JobPersistenceException { synchronized (m_triggerLock) { Trigger[] triggers = getTriggersForJob(ctxt, jobName, groupName); for (int i = 0, length = triggers.length; i < length; i++) { Trigger t = triggers[i]; resumeTrigger(ctxt, t.getName(), t.getGroup()); } } }
/** @see org.quartz.JobListener#jobToBeExecuted(JobExecutionContext) */ public void jobToBeExecuted(JobExecutionContext context) { try { ForEachListener forEachListener = new TrackNRestartListener( dataSource, tablePrefix, this.getName(), scheduler.getSchedulerName(), context.getJobDetail().getKey().getGroup(), context.getJobDetail().getKey().getName(), context.getFireInstanceId()); context.getJobDetail().getJobDataMap().put(FOR_EACH_LISTENER, forEachListener); } catch (Exception e) { TrackNRestartMessageKind.ETNRPLUGIN0002.format(e); // getLog().error("Unexpected exception.",e); } Trigger trigger = context.getTrigger(); JobDetail jobDetail = context.getJobDetail(); JobDataMap jobDataMap = jobDetail.getJobDataMap(); String params = ""; for (Iterator<Entry<String, Object>> iterator = jobDataMap.entrySet().iterator(); iterator.hasNext(); ) { Entry<String, Object> entry = (Entry<String, Object>) iterator.next(); params += entry.getKey() + "=" + entry.getValue(); if (iterator.hasNext()) { params += ", "; } } Object[] args = { jobDetail.getKey().getName(), jobDetail.getKey().getGroup(), new java.util.Date(), trigger.getKey().getName(), trigger.getKey().getGroup(), trigger.getPreviousFireTime(), trigger.getNextFireTime(), Integer.valueOf(context.getRefireCount()), context.getFireInstanceId(), params }; try { // TODO : not for JobToBeFired ? // insertJobDetail(this.getNonManagedTXConnection(), context); getLog().info(MessageFormat.format(getJobToBeFiredMessage(), args)); } catch (Exception e) { getLog().error(MessageFormat.format(getJobToBeFiredMessage(), args, e)); } }
/** * 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). * * @return null if the trigger or its job or calendar no longer exist, or if the trigger was not * successfully put into the 'executing' state. */ public TriggerFiredBundle triggerFired(SchedulingContext ctxt, Trigger trigger) throws JobPersistenceException { synchronized (m_triggerLock) { if (!isEligibleGroupName(trigger.getGroup())) { return null; } WrappedTrigger wt = m_triggersByGroupAndName.get(getTriggerKey(trigger)); if ((wt != null) && (wt.getState() == TRIGGER_STATE_CLAIMED)) { wt.setState(TRIGGER_STATE_EXECUTING); Calendar cal = null; if (trigger.getCalendarName() != null) { cal = retrieveCalendar(ctxt, trigger.getCalendarName()); } Date prevFiredTime = trigger.getPreviousFireTime(); trigger.triggered(cal); TriggerFiredBundle tfb = new TriggerFiredBundle( retrieveJob(ctxt, trigger.getJobName(), trigger.getJobGroup()), trigger, cal, false, new Date(), trigger.getPreviousFireTime(), prevFiredTime, trigger.getNextFireTime()); return tfb; } return null; } }
/** * Inform the <code>JobStore</code> that the scheduler has completed the firing of the given * <code>Trigger</code> (and the execution its associated <code>Job</code>), and that the <code> * {@link org.quartz.JobDataMap}</code> in the given <code>JobDetail</code> should be updated if * the <code>Job</code> is stateful. */ public void triggeredJobComplete( SchedulingContext ctxt, Trigger trigger, JobDetail jobDetail, int triggerInstCode) throws JobPersistenceException { synchronized (m_triggerLock) { if (trigger.getNextFireTime() != null) { storeTrigger(ctxt, trigger, true); } else { removeTrigger(ctxt, trigger.getName(), trigger.getGroup()); } } }
private long scoreTrigger(SchedulingContext ctxt, Trigger t) throws JobPersistenceException { JobDetail jd = retrieveJob(ctxt, t.getJobName(), t.getJobGroup()); if (jd == null) { return t.getNextFireTime().getTime(); } JobDataMap jdMap = jd.getJobDataMap(); int taskPriority = jdMap.getInt("taskPriority"); int custPriority = jdMap.getInt("custPriority"); long scheduledTime = t.getNextFireTime().getTime(); return computeScore(taskPriority, custPriority, scheduledTime); }
public Trigger getTrigger() { Trigger trigger = null; if (getClass().equals(SimpleTriggerDescriptor.class)) { trigger = new SimpleTrigger(name, group); } else { trigger = new CronTrigger(name, group); } trigger.setJobName(jobName); trigger.setJobGroup(group); trigger.setStartTime(dateTimeService.getCurrentDate()); completeTriggerDescription(trigger); return trigger; }
protected boolean triggerChanged(Trigger checkTrigger) { try { Trigger trigger = resourceScheduler.getTrigger(checkTrigger.getName(), checkTrigger.getGroup()); if (trigger != null && trigger instanceof CronTrigger) { return !((CronTrigger) trigger) .getCronExpression() .equals(((CronTrigger) checkTrigger).getCronExpression()); } } catch (SchedulerException e) { log.error("Failed to check if the trigger has changed", e); } return false; }
public void scheduleRoute(Action action, Route route) throws Exception { JobDetail jobDetail = createJobDetail(action, route); Trigger trigger = createTrigger(action, route); updateScheduledRouteDetails(action, jobDetail, trigger, route); loadCallbackDataIntoSchedulerContext(jobDetail, action, route); getScheduler().scheduleJob(jobDetail, trigger); if (LOG.isInfoEnabled()) { LOG.info( "Scheduled trigger: {} for action: {} on route {}", new Object[] {trigger.getKey(), action, route.getId()}); } }
/** * Get all of the Triggers that are associated to the given Job. * * <p>If there are no matches, a zero-length array should be returned. */ public Trigger[] getTriggersForJob(SchedulingContext ctxt, String jobName, String groupName) throws JobPersistenceException { // NOTE: this is linear in the number of known triggers - we may want this to be faster List<Trigger> triggers = new LinkedList<Trigger>(); synchronized (m_triggerLock) { for (Iterator<WrappedTrigger> it = m_triggersByGroupAndName.values().iterator(); it.hasNext(); ) { WrappedTrigger wt = it.next(); Trigger t = wt.getTrigger(); if ((t.getJobGroup().equals(groupName)) && (t.getJobName().equals(jobName))) { triggers.add(t); } } } return triggers.toArray(new Trigger[triggers.size()]); }
protected void schedule( Scheduler scheduler, StorageType storageType, Trigger trigger, String description, String destinationName, Message message) throws Exception { if (_jsonFactory == null) { throw new IllegalStateException("JSON factory not initialized"); } try { JobBuilder jobBuilder = JobBuilder.newJob(MessageSenderJob.class); jobBuilder.withIdentity(trigger.getJobKey()); jobBuilder.storeDurably(); JobDetail jobDetail = jobBuilder.build(); JobDataMap jobDataMap = jobDetail.getJobDataMap(); jobDataMap.put(SchedulerEngine.DESCRIPTION, description); jobDataMap.put(SchedulerEngine.DESTINATION_NAME, destinationName); jobDataMap.put(SchedulerEngine.MESSAGE, _jsonFactory.serialize(message)); jobDataMap.put(SchedulerEngine.STORAGE_TYPE, storageType.toString()); JobState jobState = new JobState( TriggerState.NORMAL, message.getInteger(SchedulerEngine.EXCEPTIONS_MAX_SIZE)); jobDataMap.put(SchedulerEngine.JOB_STATE, JobStateSerializeUtil.serialize(jobState)); unregisterMessageListener(scheduler, trigger.getJobKey()); synchronized (this) { scheduler.deleteJob(trigger.getJobKey()); scheduler.scheduleJob(jobDetail, trigger); } } catch (ObjectAlreadyExistsException oaee) { if (_log.isInfoEnabled()) { _log.info("Message is already scheduled"); } } }
public void afterPropertiesSet() throws ParseException { customTrigger = BeanUtils.instantiateClass(triggerClass); if (triggerAttributes.containsKey(QuartzConstants.START_DELAY)) { Number startDelay = (Number) triggerAttributes.remove(QuartzConstants.START_DELAY); customTrigger.setStartTime(new Date(System.currentTimeMillis() + startDelay.longValue())); } if (jobDetail != null) { customTrigger.setJobName(jobDetail.getName()); customTrigger.setJobGroup(jobDetail.getGroup()); } BeanWrapper customTriggerWrapper = PropertyAccessorFactory.forBeanPropertyAccess(customTrigger); customTriggerWrapper.registerCustomEditor(String.class, new StringEditor()); customTriggerWrapper.setPropertyValues(triggerAttributes); }
protected void updateScheduledRouteDetails( Action action, JobDetail jobDetail, Trigger trigger, Route route) throws Exception { ScheduledRouteDetails scheduledRouteDetails = getScheduledRouteDetails(route.getId()); if (action == Action.START) { scheduledRouteDetails.setStartJobKey(jobDetail.getKey()); scheduledRouteDetails.setStartTriggerKey(trigger.getKey()); } else if (action == Action.STOP) { scheduledRouteDetails.setStopJobKey(jobDetail.getKey()); scheduledRouteDetails.setStopTriggerKey(trigger.getKey()); } else if (action == Action.SUSPEND) { scheduledRouteDetails.setSuspendJobKey(jobDetail.getKey()); scheduledRouteDetails.setSuspendTriggerKey(trigger.getKey()); } else if (action == Action.RESUME) { scheduledRouteDetails.setResumeJobKey(jobDetail.getKey()); scheduledRouteDetails.setResumeTriggerKey(trigger.getKey()); } }
@Override public void execute(JobExecutionContext context) throws JobExecutionException { BundleManagerLocal bundleManager = LookupUtil.getBundleManager(); SubjectManagerLocal subjectManager = LookupUtil.getSubjectManager(); Subject overlord = subjectManager.getOverlord(); PageList<BundleDeployment> deployments = bundleManager.findBundleDeploymentsByCriteria(overlord, getCriteriaFromContext(context)); if (deployments.size() > 0) { BundleDeployment bundleDeployment = deployments.get(0); SchedulerLocal scheduler = LookupUtil.getSchedulerBean(); JobDetail jobDetail = context.getJobDetail(); BundleDeploymentStatus bundleDeploymentStatus = bundleManager.determineBundleDeploymentStatus(bundleDeployment.getId()); if (bundleDeploymentStatus.isTerminal()) { // delete this job, we've assigned a final status try { context.setResult(bundleDeploymentStatus); // Return status to possible listeners scheduler.deleteJob(jobDetail.getName(), jobDetail.getGroup()); } catch (SchedulerException e) { throw new JobExecutionException( "Could not delete the bundle deployment completion check job for " + bundleDeployment + ".", e); } } else { // try again in 10s try { Trigger trigger = QuartzUtil.getFireOnceOffsetTrigger(jobDetail, 10000L); // just need a trigger name unique for this job trigger.setName(String.valueOf(System.currentTimeMillis())); scheduler.scheduleJob(trigger); } catch (SchedulerException e) { throw new JobExecutionException( "Could not schedule the bundle deployment completion check job for " + bundleDeployment + ".", e); } } } }
public void processIntervalTrigger(final IntervalTriggerDetail intervalTriggerDetails) throws ParseException, SchedulerException, InternalError { Trigger schedTrigger = null; if (SECOND.equals(intervalTriggerDetails.getRepeatUnit())) { schedTrigger = TriggerUtils.makeSecondlyTrigger(intervalTriggerDetails.getRepeatInterval()); } else if (MINUTE.equals(intervalTriggerDetails.getRepeatUnit())) { schedTrigger = TriggerUtils.makeMinutelyTrigger(intervalTriggerDetails.getRepeatInterval()); } else if (HOUR.equals(intervalTriggerDetails.getRepeatUnit())) { schedTrigger = TriggerUtils.makeHourlyTrigger(intervalTriggerDetails.getRepeatInterval()); } else { throw new InternalError( "Could not work out which interval to use for the schedule of an @" + Every.class.getName() + " observer"); } schedTrigger.setJobGroup(SCHEDULE_JOB_GROUP); scheduleJob(schedTrigger, intervalTriggerDetails); }
/** * Returns the previous time at which this job will be executed. * * <p>If this job has not yet been executed, <code>null</code> will be returned. * * @return the previous time at which this job will be executed */ public Date getExecutionTimePrevious() { if (!m_active || (m_trigger == null)) { // if the job is not active, no time can be calculated return null; } return m_trigger.getPreviousFireTime(); }
/** * Returns the next time at which this job will be executed, after the given time. * * <p>If this job will not be executed after the given time, <code>null</code> will be returned.. * * <p> * * @param date the after which the next execution time should be calculated * @return the next time at which this job will be executed, after the given time */ public Date getExecutionTimeAfter(Date date) { if (!m_active || (m_trigger == null)) { // if the job is not active, no time can be calculated return null; } return m_trigger.getFireTimeAfter(date); }
/** @see org.quartz.JobListener#jobWasExecuted(JobExecutionContext, JobExecutionException) */ public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) { Trigger trigger = context.getTrigger(); Object[] args = null; Object oResult = context.getResult(); String result = showJobDataMap(oResult); if (jobException != null) { String errMsg = jobException.getMessage(); args = new Object[] { context.getJobDetail().getKey().getName(), context.getJobDetail().getKey().getGroup(), new java.util.Date(), trigger.getKey().getName(), trigger.getKey().getGroup(), trigger.getPreviousFireTime(), trigger.getNextFireTime(), Integer.valueOf(context.getRefireCount()), context.getFireInstanceId(), result, errMsg }; try { insertJobDetail(this.getNonManagedTXConnection(), context); getLog().info(MessageFormat.format(getJobFailedMessage(), args)); // without exception trace // getLog().info(MessageFormat.format(getJobFailedMessage(), args), // jobException); } catch (Exception e) { getLog().error(MessageFormat.format(getJobFailedMessage(), args, e)); } } else { args = new Object[] { context.getJobDetail().getKey().getName(), context.getJobDetail().getKey().getGroup(), new java.util.Date(), trigger.getKey().getName(), trigger.getKey().getGroup(), trigger.getPreviousFireTime(), trigger.getNextFireTime(), Integer.valueOf(context.getRefireCount()), context.getFireInstanceId(), result }; try { insertJobDetail(this.getNonManagedTXConnection(), context); getLog().info(MessageFormat.format(getJobSuccessMessage(), args)); } catch (Exception e) { getLog().error(MessageFormat.format(getJobSuccessMessage(), args, e)); } } }
public void triggerFired(Trigger trigger, JobExecutionContext jobExecutionContext) { eventManager.createTriggerEvent( TriggerEvent.TRIGGER_EVENT_TYPE.FIRED, jobExecutionContext.getJobDetail().getKey(), trigger.getKey(), new Date(), "Trigger fired", getServerId()); }
@Override public void visit(FixedPeriodJobTrigger trigger) { switch (trigger.getTimeUnit()) { case SECOND: quartzTrigger = TriggerUtils.makeSecondlyTrigger(trigger.getTimeInterval()); break; case MINUTE: quartzTrigger = TriggerUtils.makeMinutelyTrigger(trigger.getTimeInterval()); break; case HOUR: quartzTrigger = TriggerUtils.makeHourlyTrigger(trigger.getTimeInterval()); break; } if (trigger.getStartDate() != null) { quartzTrigger.setStartTime(trigger.getStartDate()); } else { quartzTrigger.setStartTime(quartzTrigger.getFireTimeAfter(new Date())); } }
@Override protected Trigger getTrigger() { final TriggerBuilder<? extends Trigger> triggerBuilder = trigger.getTriggerBuilder(); triggerBuilder.withIdentity((TriggerKey) null); if (getDelay() != null) { triggerBuilder.startAt(new DateTime().plus(getDelay()).toDate()); } return triggerBuilder.build(); }
/** * Trigger被激发 它关联的job即将被运行 Called by the Scheduler when a Trigger has fired, and it's associated * JobDetail is about to be executed. * * @param trigger * @param context */ public void triggerFired(Trigger trigger, JobExecutionContext context) { TriggerKey triggerKey = trigger.getKey(); String name = triggerKey.getName(); String group = triggerKey.getGroup(); System.out.println( "Trigger监听器:QuartzTriggerListener.triggerFired(),[name = " + name + ",group = " + group + "]"); }
/** * 获取下次作业触发时间. * * @return 下次作业触发时间 */ public Date getNextFireTime() { Date result = null; List<? extends Trigger> triggers; try { triggers = scheduler.getTriggersOfJob(jobDetail.getKey()); } catch (final SchedulerException ex) { return result; } for (Trigger each : triggers) { Date nextFireTime = each.getNextFireTime(); if (null == nextFireTime) { continue; } if (null == result) { result = nextFireTime; } else if (nextFireTime.getTime() < result.getTime()) { result = nextFireTime; } } return result; }