Java Code Examples for org.quartz.Trigger

The following examples show how to use org.quartz.Trigger. These examples are extracted from open source projects. 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 Project: spring-batch-rest   Source File: AdHocScheduler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Schedules a Spring Batch job via a Quartz cron expression. Also registers the
 * job with the specified jobName, rather than the job param's name
 */
public synchronized Job schedule(String jobName, Job job, String cronExpression) {
	log.debug("Scheduling job {} with CRON expression {}", jobName, cronExpression);
	try {
		jobBuilder.registerJob(job);
		JobDetail jobDetail = this.jobDetailFor(jobName);

		Trigger trigger = TriggerUtil.triggerFor(cronExpression, jobName);

		scheduler.unscheduleJob(trigger.getKey());
		scheduler.scheduleJob(jobDetail, trigger);
		log.info("Scheduled job {} with CRON expression {}", jobName, cronExpression);
	} catch (Exception e) {
		throw new RuntimeException(format("Can't schedule job %s with cronExpression %s", jobName, cronExpression),
				e);
	}
	return job;
}
 
Example 2
Source Project: griffin   Source File: JobInstanceTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testExecuteWithRangeGreaterThanDataUnit() throws Exception {
    JobExecutionContext context = mock(JobExecutionContext.class);
    Scheduler scheduler = mock(Scheduler.class);
    GriffinMeasure measure = createGriffinMeasure("measureName");
    JobDetail jd = createJobDetail(JsonUtil.toJson(measure), "");
    BatchJob job = new BatchJob(1L, "jobName", "qName", "qGroup", false);
    List<Trigger> triggers = Arrays.asList(createSimpleTrigger(2, 0));
    given(context.getJobDetail()).willReturn(jd);
    given(measureRepo.findOne(Matchers.anyLong())).willReturn(measure);
    given(jobRepo.findOne(Matchers.anyLong())).willReturn(job);
    given(factory.getScheduler()).willReturn(scheduler);
    given((List<Trigger>) scheduler.getTriggersOfJob(Matchers.any(
            JobKey.class))).willReturn(triggers);
    given(scheduler.checkExists(Matchers.any(TriggerKey.class)))
            .willReturn(false);
    given(jobRepo.save(Matchers.any(BatchJob.class))).willReturn(job);
    given(scheduler.checkExists(Matchers.any(JobKey.class)))
            .willReturn(false);
    jobInstance.execute(context);

    verify(context, times(1)).getJobDetail();

}
 
Example 3
Source Project: springboot-quartz   Source File: ScheduleJobService.java    License: MIT License 6 votes vote down vote up
public List<ScheduleJob> getAllJobList(){  
    List<ScheduleJob> jobList = new ArrayList<>();  
    try {  
        GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();  
        Set<JobKey> jobKeySet = scheduler.getJobKeys(matcher);  
        for (JobKey jobKey : jobKeySet){  
            List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);  
            for (Trigger trigger : triggers){  
                ScheduleJob scheduleJob = new ScheduleJob();  
                this.wrapScheduleJob(scheduleJob,scheduler,jobKey,trigger);  
                jobList.add(scheduleJob);  
            }  
        }  
    } catch (SchedulerException e) {  
    	e.printStackTrace();   
    }  
    return jobList;  
}
 
Example 4
Source Project: AsuraFramework   Source File: QuartzScheduler.java    License: Apache License 2.0 6 votes vote down vote up
public void notifyTriggerListenersMisfired(Trigger trigger)
    throws SchedulerException {
    // build a list of all trigger listeners that are to be notified...
    List triggerListeners = buildTriggerListenerList(trigger
            .getTriggerListenerNames());

    // notify all trigger listeners in the list
    java.util.Iterator itr = triggerListeners.iterator();
    while (itr.hasNext()) {
        TriggerListener tl = (TriggerListener) itr.next();
        try {
            tl.triggerMisfired(trigger);
        } catch (Exception e) {
            SchedulerException se = new SchedulerException(
                    "TriggerListener '" + tl.getName()
                            + "' threw exception: " + e.getMessage(), e);
            se.setErrorCode(SchedulerException.ERR_TRIGGER_LISTENER);
            throw se;
        }
    }
}
 
Example 5
/**
 * Refresh metadata. Schedules the job to retrieve metadata.
 * @throws SchedulerException the scheduler exception
 */
@PostConstruct
public void refreshMetadata() throws SchedulerException {
    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            buildMetadataResolverAggregate();
        }
    });
    thread.start();

    final JobDetail job = JobBuilder.newJob(this.getClass())
            .withIdentity(this.getClass().getSimpleName()).build();
    final Trigger trigger = TriggerBuilder.newTrigger()
            .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInMinutes(this.refreshIntervalInMinutes)
                    .repeatForever()).build();

    final SchedulerFactory schFactory = new StdSchedulerFactory();
    final Scheduler sch = schFactory.getScheduler();
    sch.start();
    sch.scheduleJob(job, trigger);
}
 
Example 6
/**
 * {@inheritDoc}
 */
public void triggerFired(Trigger trigger, JobExecutionContext ctx) {
    // Insure that Hibernate is in a valid state before executing the task
    // Need to synchronize this because the method get called by multiple
    // scheduler threads concurrently
    synchronized (this) {
        try {
            HibernateFactory.initialize();
            if (!HibernateFactory.isInitialized()) {
                logger.error("HibernateFactory failed to initialize");
                this.vetoedJobs.put(new Integer(ctx.hashCode()), Boolean.TRUE);
            }
        }
        catch (Throwable t) {
            logger.error(t.getLocalizedMessage(), t);
            this.vetoedJobs.put(new Integer(ctx.hashCode()), Boolean.TRUE);
        }
    }
}
 
Example 7
/**
 * <p>
 * Get the current state of the identified <code>{@link Trigger}</code>.
 * </p>
 * 
 * @see Trigger.TriggerState
 */
@Override
public Trigger.TriggerState getTriggerState(org.quartz.TriggerKey key) throws JobPersistenceException {

  TriggerWrapper tw;
  lock();
  try {
    tw = triggerFacade.get(key);
  } finally {
    unlock();
  }

  if (tw == null) { return Trigger.TriggerState.NONE; }

  if (tw.getState() == TriggerState.COMPLETE) { return Trigger.TriggerState.COMPLETE; }

  if (tw.getState() == TriggerState.PAUSED) { return Trigger.TriggerState.PAUSED; }

  if (tw.getState() == TriggerState.PAUSED_BLOCKED) { return Trigger.TriggerState.PAUSED; }

  if (tw.getState() == TriggerState.BLOCKED) { return Trigger.TriggerState.BLOCKED; }

  if (tw.getState() == TriggerState.ERROR) { return Trigger.TriggerState.ERROR; }

  return Trigger.TriggerState.NORMAL;
}
 
Example 8
Source Project: attic-aurora   Source File: CronJobManagerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateExistingJob() throws Exception {
  SanitizedCronJob sanitizedCronJob = QuartzTestUtil.makeSanitizedCronJob();

  expect(scheduler.deleteJob(QuartzTestUtil.QUARTZ_JOB_KEY)).andReturn(true);
  expect(scheduler.scheduleJob(anyObject(JobDetail.class), anyObject(Trigger.class)))
     .andReturn(null);

  populateStorage();

  control.replay();

  cronJobManager.updateJob(sanitizedCronJob);
  assertEquals(
      sanitizedCronJob.getSanitizedConfig().getJobConfig(),
      fetchFromStorage().orElse(null));
}
 
Example 9
Source Project: seed   Source File: QssService.java    License: Apache License 2.0 6 votes vote down vote up
private ScheduleTask convertToScheduleTask(JobKey jobKey, Trigger trigger) throws SchedulerException {
    ScheduleTask task = new ScheduleTask();
    String[] jobname = jobKey.getName().split(":");
    task.setId(Long.parseLong(jobname[0]));
    task.setAppname(jobname[1]);
    task.setName(jobname[2]);
    //task.setGroup(jobKey.getGroup());
    //task.setDesc("触发器[" + trigger.getKey() + "]");
    //task.setStartTime(trigger.getStartTime());             //开始时间
    //task.setEndTime(trigger.getEndTime());                 //结束时间
    task.setNextFireTime(trigger.getNextFireTime());         //下次触发时间
    task.setPreviousFireTime(trigger.getPreviousFireTime()); //上次触发时间
    if(trigger instanceof CronTrigger){
        task.setCron(((CronTrigger)trigger).getCronExpression());
    }
    Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
    task.setStatus("N".equals(triggerState.name()) ? SeedConstants.QSS_STATUS_STOP : SeedConstants.QSS_STATUS_RUNNING);
    return task;
}
 
Example 10
Source Project: mojito   Source File: QuartzSchedulerConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates the scheduler with triggers/jobs defined in spring beans.
 * <p>
 * The spring beans should use the default group so that it is easy to keep track of new or removed triggers/jobs.
 * <p>
 * In {@link #startScheduler()} triggers/jobs present in Quartz but without a matching spring bean will be
 * removed.
 * <p>
 * Other job and trigger created dynamically must not used the default group else they'll be removed.
 *
 * @return
 * @throws SchedulerException
 */
@Bean
public SchedulerFactoryBean scheduler() throws SchedulerException {

    logger.info("Create SchedulerFactoryBean");

    Properties quartzProperties = quartzPropertiesConfig.getQuartzProperties();

    SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();

    String dataSource = quartzProperties.getProperty("org.quartz.jobStore.dataSource");
    schedulerFactory.setQuartzProperties(quartzProperties);
    schedulerFactory.setJobFactory(springBeanJobFactory());
    schedulerFactory.setOverwriteExistingJobs(true);
    schedulerFactory.setTriggers(triggers.toArray(new Trigger[]{}));
    schedulerFactory.setAutoStartup(false);

    return schedulerFactory;
}
 
Example 11
Source Project: lams   Source File: CronTriggerImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>
 * Updates the <code>CronTrigger</code>'s state based on the
 * MISFIRE_INSTRUCTION_XXX that was selected when the <code>CronTrigger</code>
 * was created.
 * </p>
 * 
 * <p>
 * If the misfire instruction is set to MISFIRE_INSTRUCTION_SMART_POLICY,
 * then the following scheme will be used: <br>
 * <ul>
 * <li>The instruction will be interpreted as <code>MISFIRE_INSTRUCTION_FIRE_ONCE_NOW</code>
 * </ul>
 * </p>
 */
@Override
public void updateAfterMisfire(org.quartz.Calendar cal) {
    int instr = getMisfireInstruction();

    if(instr == Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY)
        return;

    if (instr == MISFIRE_INSTRUCTION_SMART_POLICY) {
        instr = MISFIRE_INSTRUCTION_FIRE_ONCE_NOW;
    }

    if (instr == MISFIRE_INSTRUCTION_DO_NOTHING) {
        Date newFireTime = getFireTimeAfter(new Date());
        while (newFireTime != null && cal != null
                && !cal.isTimeIncluded(newFireTime.getTime())) {
            newFireTime = getFireTimeAfter(newFireTime);
        }
        setNextFireTime(newFireTime);
    } else if (instr == MISFIRE_INSTRUCTION_FIRE_ONCE_NOW) {
        setNextFireTime(new Date());
    }
}
 
Example 12
Source Project: nexus-public   Source File: QuartzSchedulerSPI.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Schedules a manually executable trigger for a job missing a trigger and adds marker for health check reporting
 */
private Trigger scheduleJobWithManualTrigger(final JobKey jobKey,
                                             final JobDetail jobDetail,
                                             final TriggerKey triggerKey) throws SchedulerException
{
  log.error("Missing trigger for key: {}", jobKey);
  Trigger trigger = triggerConverter.convert(new Manual())
      .usingJobData(jobDetail.getJobDataMap())
      .usingJobData(MISSING_TRIGGER_RECOVERY, jobKey.getName())
      .withIdentity(triggerKey)
      .withDescription(jobDetail.getDescription())
      .forJob(jobDetail)
      .build();
  log.info("Rescheduling job '{}' with manual trigger", jobDetail.getDescription());
  scheduler.scheduleJob(trigger);
  return trigger;
}
 
Example 13
public void triggerComplete(
		Trigger trigger,
		JobExecutionContext context,
		Trigger.CompletedExecutionInstruction triggerInstructionCode) {
	// Check it's one of ours
	if (GROUP_NAME.equals(trigger.getKey().getGroup())) {
		String contextId = trigger.getJobDataMap().getString(CONTEXT_ID);
		if (contextId == null) {
			log.warn("One of our triggers ({}) didn't have a context ID", trigger.getKey());
		} else {
			dao.remove(trigger.getJobKey().getName(), contextId);
		}
	}
}
 
Example 14
Source Project: AsuraFramework   Source File: RemoteMBeanScheduler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Calls the equivalent method on the 'proxied' <code>QuartzScheduler</code>,
 * passing the <code>SchedulingContext</code> associated with this
 * instance.
 * </p>
 */
public Date rescheduleJob(String triggerName,
        String groupName, Trigger newTrigger) throws SchedulerException {
    return (Date)invoke(
            "unscheduleJob", 
            new Object[] { schedulingContext, triggerName, groupName, newTrigger}, 
            new String[] { SchedulingContext.class.getName(), String.class.getName(), String.class.getName(), Trigger.class.getName() });
}
 
Example 15
Source Project: cachecloud   Source File: RedisCenterImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean unDeployRedisCollection(long appId, String host, int port) {
    Assert.isTrue(appId > 0);
    Assert.hasText(host);
    Assert.isTrue(port > 0);
    TriggerKey triggerKey = TriggerKey
            .triggerKey(ObjectConvert.linkIpAndPort(host, port), ConstUtils.REDIS_TRIGGER_GROUP + appId);
    Trigger trigger = schedulerCenter.getTrigger(triggerKey);
    if (trigger == null) {
        return true;
    }
    return schedulerCenter.unscheduleJob(triggerKey);
}
 
Example 16
Source Project: AsuraFramework   Source File: QuartzScheduler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Trigger the identified <code>{@link org.quartz.Job}</code> (execute it
 * now) - with a volatile trigger.
 * </p>
 */
public void triggerJobWithVolatileTrigger(SchedulingContext ctxt,
        String jobName, String groupName, JobDataMap data) throws SchedulerException {
    validateState();

    if(groupName == null) {
        groupName = Scheduler.DEFAULT_GROUP;
    }
    
    Trigger trig = new org.quartz.SimpleTrigger(newTriggerId(),
            Scheduler.DEFAULT_MANUAL_TRIGGERS, jobName, groupName,
            new Date(), null, 0, 0);
    trig.setVolatility(true);
    trig.computeFirstFireTime(null);
    if(data != null) {
        trig.setJobDataMap(data);
    }
    
    boolean collision = true;
    while (collision) {
        try {
            resources.getJobStore().storeTrigger(ctxt, trig, false);
            collision = false;
        } catch (ObjectAlreadyExistsException oaee) {
            trig.setName(newTriggerId());
        }
    }

    notifySchedulerThread(trig.getNextFireTime().getTime());
    notifySchedulerListenersSchduled(trig);
}
 
Example 17
Source Project: cachecloud   Source File: MachineCenterImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean unDeployServerCollection(long hostId, String ip) {
       Assert.hasText(ip);
       TriggerKey collectionTriggerKey = TriggerKey.triggerKey(ip, ConstUtils.SERVER_TRIGGER_GROUP + ip);
       Trigger trigger = schedulerCenter.getTrigger(collectionTriggerKey);
       if (trigger == null) {
           return true;
       }
       return schedulerCenter.unscheduleJob(collectionTriggerKey);
}
 
Example 18
public JobQuartzAutoConfiguration(QuartzProperties properties, JobServerProperties jobServerProperties, ObjectProvider<SchedulerFactoryBeanCustomizer> customizers, ObjectProvider<JobDetail[]> jobDetails, ObjectProvider<Map<String, Calendar>> calendars, ObjectProvider<Trigger[]> triggers, ApplicationContext applicationContext) {
    this.properties = properties;
    this.jobServerProperties = jobServerProperties;
    this.customizers = customizers;
    this.jobDetails = (JobDetail[]) jobDetails.getIfAvailable();
    this.calendars = (Map) calendars.getIfAvailable();
    this.triggers = (Trigger[]) triggers.getIfAvailable();
    this.applicationContext = applicationContext;
    // 初始化job属性配置信息
    initJobProperties(this.properties);
}
 
Example 19
Source Project: mangooio   Source File: SchedulerUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateTriggerCron() {
    //given
    String identity = "foo";
    String groupName = "bar";
    String description = "description";
    String cron = "0 0 3 * * ?";
    
    //when
    Trigger trigger = SchedulerUtils.createTrigger(identity, groupName, description, cron);
    
    //then
    assertThat(trigger, not(nullValue()));
    assertThat(trigger.getDescription(), equalTo(description));
}
 
Example 20
Source Project: incubator-gobblin   Source File: QuartzJobSpecScheduler.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override protected JobSpecSchedule doScheduleJob(JobSpec jobSpec, Runnable jobRunnable) {

  // Build a data map that gets passed to the job
  JobDataMap jobDataMap = new JobDataMap();
  jobDataMap.put(JOB_SPEC_KEY, jobSpec);
  jobDataMap.put(JOB_RUNNABLE_KEY, jobRunnable);

  // Build a Quartz job
  JobDetail job = JobBuilder.newJob(QuartzJob.class)
      .withIdentity(jobSpec.getUri().toString())
      .withDescription(Strings.nullToEmpty(jobSpec.getDescription()))
      .usingJobData(jobDataMap)
      .build();

  Trigger jobTrigger = createTrigger(job.getKey(), jobSpec);
  QuartzJobSchedule jobSchedule = new QuartzJobSchedule(jobSpec, jobRunnable, jobTrigger);
  try {
    _scheduler.getScheduler().scheduleJob(job, jobTrigger);
    getLog().info(String.format("Scheduled job %s next two fire times: %s , %s.", jobSpec, jobTrigger.getNextFireTime(),
        jobTrigger.getFireTimeAfter(jobTrigger.getNextFireTime())));
  } catch (SchedulerException e) {
    throw new RuntimeException("Scheduling failed for " + jobSpec + ":" + e, e);
  }

  return jobSchedule;
}
 
Example 21
Source Project: fixflow   Source File: Test.java    License: Apache License 2.0 5 votes vote down vote up
public void task() throws SchedulerException {
	SchedulerFactory schedulerFactory = QuartzUtil.createSchedulerFactory();
	Scheduler scheduler = QuartzUtil.getScheduler(schedulerFactory);
	Trigger tg = QuartzUtil.getTrigger(scheduler, "mytrigger");
	((SimpleTrigger)tg).getRepeatCount();
       // reschedule the job
       scheduler.rescheduleJob(new TriggerKey("mytrigger"), tg);
}
 
Example 22
Source Project: tangyuan2   Source File: TimerComponent.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void register() throws Throwable {
	for (int i = 0; i < timerList.size(); i++) {
		TimerConfig config = timerList.get(i);
		Class<? extends Job> jobClass = config.isSync() ? NonConcurrentJob.class : ConcurrentJob.class;
		JobDetail job = JobBuilder.newJob(jobClass).withIdentity("JOB" + i, JOB_GROUP_NAME).build();
		job.getJobDataMap().put("CONFIG", config);
		Trigger trigger = TriggerBuilder.newTrigger().withIdentity("TRIGGER" + i, TRIGGER_GROUP_NAME)
				.withSchedule(CronScheduleBuilder.cronSchedule(config.getScheduled())).startNow().build();
		scheduler.scheduleJob(job, trigger);
		log.info("add timer: " + config.getService());
	}
}
 
Example 23
Source Project: openhab1-addons   Source File: JobScheduler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Schedules the IntervalJob with the specified interval and starts it
 * immediately.
 */
public void scheduleIntervalJob() {
    AstroConfig config = context.getConfig();

    String jobName = IntervalJob.class.getSimpleName();
    Date start = new Date(System.currentTimeMillis() + (config.getInterval()) * 1000);
    Trigger trigger = newTrigger().withIdentity(jobName + "-Trigger", JOB_GROUP).startAt(start)
            .withSchedule(simpleSchedule().repeatForever().withIntervalInSeconds(config.getInterval())).build();

    schedule(jobName, IntervalJob.class, trigger, new JobDataMap());
    logger.info("Scheduled astro job with interval of {} seconds", config.getInterval());
}
 
Example 24
Source Project: quartz-glass   Source File: CronTriggerForm.java    License: Apache License 2.0 5 votes vote down vote up
public CronTriggerForm(Trigger trigger) {
    this.startTime = Dates.copy(trigger.getStartTime());
    this.endTime = Dates.copy(trigger.getEndTime());
    this.dataMap = JobDataMapUtils.toProperties(trigger.getJobDataMap());
    this.cronExpression = ((CronTrigger) trigger).getCronExpression();

}
 
Example 25
Source Project: lams   Source File: RemoteScheduler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>
 * Calls the equivalent method on the 'proxied' <code>QuartzScheduler</code>.
 * </p>
 */
public Date scheduleJob(JobDetail jobDetail, Trigger trigger)
    throws SchedulerException {
    try {
        return getRemoteScheduler().scheduleJob(jobDetail,
                trigger);
    } catch (RemoteException re) {
        throw invalidateHandleCreateException(
                "Error communicating with remote scheduler.", re);
    }
}
 
Example 26
Source Project: elasticsearch-quartz   Source File: ScheduleService.java    License: Apache License 2.0 5 votes vote down vote up
public Date scheduleJob(final JobDetail jobDetail, final Trigger trigger) {
    try {
        return scheduler.scheduleJob(jobDetail, trigger);
    } catch (final SchedulerException e) {
        throw new QuartzSchedulerException(e);
    }
}
 
Example 27
Source Project: AsuraFramework   Source File: JobStoreSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Get all of the Triggers that are associated to the given Job.
 * </p>
 * 
 * <p>
 * If there are no matches, a zero-length array should be returned.
 * </p>
 */
public Trigger[] getTriggersForJob(final SchedulingContext ctxt, final String jobName,
    final String groupName) throws JobPersistenceException {
    return (Trigger[])executeWithoutLock( // no locks necessary for read...
        new TransactionCallback() {
            public Object execute(Connection conn) throws JobPersistenceException {
                return getTriggersForJob(conn, ctxt, jobName, groupName);
            }
        });
}
 
Example 28
Source Project: uyuni   Source File: SingleShotListener.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean vetoJobExecution(Trigger trigger, JobExecutionContext ctx) {
    synchronized (this) {
        if (this.jobCount == 0 && !this.shutdownStarted) {
            this.shutdownStarted = true;
            this.owner.startShutdown();
        }
    }
    return false;
}
 
Example 29
Source Project: lams   Source File: SchedulerAccessor.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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) {
		return false;
	}

	// Check if the Trigger is aware of an associated JobDetail.
	JobDetail jobDetail = (JobDetail) trigger.getJobDataMap().remove("jobDetail");
	if (triggerExists) {
		if (jobDetail != null && !this.jobDetails.contains(jobDetail) && addJobToScheduler(jobDetail)) {
			this.jobDetails.add(jobDetail);
		}
		getScheduler().rescheduleJob(trigger.getKey(), trigger);
	}
	else {
		try {
			if (jobDetail != null && !this.jobDetails.contains(jobDetail) &&
					(this.overwriteExistingJobs || getScheduler().getJobDetail(jobDetail.getKey()) == null)) {
				getScheduler().scheduleJob(jobDetail, trigger);
				this.jobDetails.add(jobDetail);
			}
			else {
				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);
			}
		}
	}
	return true;
}
 
Example 30
Source Project: AsuraFramework   Source File: RemoteScheduler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Calls the equivalent method on the 'proxied' <code>QuartzScheduler</code>,
 * passing the <code>SchedulingContext</code> associated with this
 * instance.
 * </p>
 */
public Date rescheduleJob(String triggerName,
        String groupName, Trigger newTrigger) throws SchedulerException {
    try {
        return getRemoteScheduler().rescheduleJob(schedCtxt, triggerName,
                groupName, newTrigger);
    } catch (RemoteException re) {
        throw invalidateHandleCreateException(
                "Error communicating with remote scheduler.", re);
    }
}