org.quartz.Trigger Java Examples

The following examples show how to use org.quartz.Trigger. 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: QuartzScheduler.java    From AsuraFramework with 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 #2
Source File: QssService.java    From seed with 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 #3
Source File: CronJobManagerImplTest.java    From attic-aurora with 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 #4
Source File: DefaultClusteredJobStore.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <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 #5
Source File: ScheduleJobService.java    From springboot-quartz with 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 #6
Source File: TaskEnvironmentListener.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@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
Source File: StaticMetadataResolverAdapter.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * 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 #8
Source File: QuartzSchedulerConfig.java    From mojito with 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 #9
Source File: JobInstanceTest.java    From griffin with 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 #10
Source File: CronTriggerImpl.java    From lams with 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 #11
Source File: QuartzSchedulerSPI.java    From nexus-public with 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 #12
Source File: AdHocScheduler.java    From spring-batch-rest with 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 #13
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 #14
Source File: SubscriptionCronScheduler.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Override
public void startJob(AbstractBean config, JobDetail job) throws SchedulerException {
  Trigger trigger = TriggerBuilder.newTrigger().withSchedule(
      CronScheduleBuilder.cronSchedule(((DetectionAlertConfigBean) config).getCronExpression())).build();
  this.scheduler.scheduleJob(job, trigger);
  LOG.info(String.format("scheduled subscription pipeline job %s", job.getKey().getName()));
}
 
Example #15
Source File: SchedulerAccessor.java    From lams with 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 #16
Source File: SchedulerAccessor.java    From spring4-understanding with Apache License 2.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 #17
Source File: Scheduler.java    From mangooio with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a new job with a given JobDetail and Trigger to the scheduler 
 * 
 * @param jobDetail The JobDetail for the Job
 * @param trigger The Trigger for the job
 * @throws MangooSchedulerException when accessing the scheduler results in an error
 */
public void schedule(JobDetail jobDetail, Trigger trigger) throws MangooSchedulerException {
    Objects.requireNonNull(jobDetail, Required.JOB_DETAIL.toString());
    Objects.requireNonNull(trigger, Required.TRIGGER.toString());
    Objects.requireNonNull(this.quartzScheduler, Required.SCHEDULER.toString());

    try {
        this.quartzScheduler.scheduleJob(jobDetail, trigger);
    } catch (final SchedulerException e) {
        throw new MangooSchedulerException(e);
    }
}
 
Example #18
Source File: SystemJobHelper.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Starts a system job asynchronously.
 *
 * @param jobName the system job name (case-sensitive)
 * @param parameters the list of parameters
 *
 * @throws org.quartz.SchedulerException if fails to schedule the system job
 */
public void runSystemJob(String jobName, List<Parameter> parameters) throws SchedulerException
{
    // Validate the system job name.
    AbstractSystemJob systemJob;
    try
    {
        systemJob = (AbstractSystemJob) applicationContext.getBean(jobName);
    }
    catch (Exception e)
    {
        throw new ObjectNotFoundException(String.format("System job with name \"%s\" doesn't exist.", jobName), e);
    }

    // Validate parameters per relative system job.
    systemJob.validateParameters(parameters);

    // Prepare a trigger to run the system job only once.
    TriggerKey triggerKey = TriggerKey.triggerKey(jobName + AbstractSystemJob.RUN_ONCE_TRIGGER_SUFFIX);
    Trigger trigger = newTrigger().withIdentity(triggerKey).forJob(jobName).usingJobData(systemJob.getJobDataMap(parameters)).startNow().build();

    LOGGER.debug(String.format("schedule job with trigger: calendarName: %s, description: %s, endTime: %s, finalFireTime: %s, jobKey: %s, key: %s, " +
        "misfireInstruction: %s, nextFireTime: %s, previousFireTime: %s, priority: %s, startTime: %s", trigger.getCalendarName(), trigger.getDescription(),
        trigger.getEndTime(), trigger.getFinalFireTime(), trigger.getJobKey(), trigger.getKey(), trigger.getMisfireInstruction(), trigger.getNextFireTime(),
        trigger.getPreviousFireTime(), trigger.getPriority(), trigger.getStartTime()));

    // Schedule the system job.
    schedulerFactory.getScheduler().scheduleJob(trigger);
}
 
Example #19
Source File: SchedulerTriggerListener.java    From dapeng-soa with Apache License 2.0 5 votes vote down vote up
/**
 * (1)
 * Trigger被激发 它关联的job即将被运行
 * Called by the Scheduler when a Trigger has fired, and it's associated JobDetail is about to be executed.
 */
@Override
public void triggerFired(Trigger trigger, JobExecutionContext context) {
    TaskMonitorDataReportUtils.setSessionTid(null);

    JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
    String serviceName = jobDataMap.getString("serviceName");
    String versionName = jobDataMap.getString("versionName");
    String methodName = jobDataMap.getString("methodName");

    String message = String.format("SchedulerTriggerListener::triggerFired;Task[%s:%s:%s] 即将被触发", serviceName, versionName, methodName);
    //sendMessage(serviceName, versionName, methodName, message, false, jobDataMap, "normal");
}
 
Example #20
Source File: RemoteScheduler.java    From lams with 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 Trigger getTrigger(TriggerKey triggerKey)
    throws SchedulerException {
    try {
        return getRemoteScheduler().getTrigger(triggerKey);
    } catch (RemoteException re) {
        throw invalidateHandleCreateException(
                "Error communicating with remote scheduler.", re);
    }
}
 
Example #21
Source File: DetectionCronScheduler.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Override
public void startJob(AbstractBean config, JobDetail job) throws SchedulerException {
  Trigger trigger = TriggerBuilder.newTrigger().withSchedule(
      CronScheduleBuilder.cronSchedule(((DetectionConfigBean) config).getCron())).build();
  this.scheduler.scheduleJob(job, trigger);
  LOG.info(String.format("scheduled detection pipeline job %s", job.getKey().getName()));
}
 
Example #22
Source File: RemoteScheduler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void scheduleJobs(Map<JobDetail, Set<? extends Trigger>> triggersAndJobs, boolean replace) throws SchedulerException {
        try {
            getRemoteScheduler().scheduleJobs(triggersAndJobs, replace);
        } catch (RemoteException re) {
            throw invalidateHandleCreateException(
                    "Error communicating with remote scheduler.", re);
        }
}
 
Example #23
Source File: RedisCenterImpl.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
@Override
public boolean unDeployRedisSlowLogCollection(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_SLOWLOG_TRIGGER_GROUP + appId);
    Trigger trigger = schedulerCenter.getTrigger(triggerKey);
    if (trigger == null) {
        return true;
    }
    return schedulerCenter.unscheduleJob(triggerKey);
}
 
Example #24
Source File: QuartzSchedulerSPI.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Attach {@link QuartzTaskJobListener} to job.
 */
private QuartzTaskJobListener attachJobListener(final JobDetail jobDetail,
                                                final Trigger trigger) throws SchedulerException
{
  log.debug("Initializing task-state: jobDetail={}, trigger={}", jobDetail, trigger);

  Date now = new Date();
  TaskConfiguration taskConfiguration = configurationOf(jobDetail);
  Schedule schedule = triggerConverter.convert(trigger);
  QuartzTaskState taskState = new QuartzTaskState(
      taskConfiguration,
      schedule,
      trigger.getFireTimeAfter(now)
  );

  QuartzTaskFuture future = null;
  if (schedule instanceof Now) {
    future = new QuartzTaskFuture(
        this,
        jobDetail.getKey(),
        taskConfiguration.getTaskLogName(),
        now,
        schedule,
        null
    );
  }

  QuartzTaskJobListener listener = new QuartzTaskJobListener(
      listenerName(jobDetail.getKey()),
      eventManager,
      this,
      new QuartzTaskInfo(eventManager, this, jobDetail.getKey(), taskState, future)
  );

  scheduler.getListenerManager().addJobListener(listener, keyEquals(jobDetail.getKey()));

  return listener;
}
 
Example #25
Source File: Context.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends AbstractJob> void scheduleLocal(Class<T> cls, Integer delay, Integer interval) throws Exception {
	JobDataMap jobDataMap = new JobDataMap();
	jobDataMap.put("context", this);
	JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(cls.getName(), clazz.getName())
			.usingJobData(jobDataMap).withDescription(Config.node()).build();
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(cls.getName(), clazz.getName())
			.withDescription("scheduleLocal").startAt(DateBuilder.futureDate(delay, IntervalUnit.SECOND))
			.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(interval).repeatForever())
			.build();
	scheduler.scheduleJob(jobDetail, trigger);
	this.scheduleLocalRequestList.add(new ScheduleLocalRequest(jobDetail, null, delay, interval));
}
 
Example #26
Source File: ChainedListener.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void triggerMisfired(Trigger trigger) {
    for (Iterator iter = this.listenerChain.iterator(); iter.hasNext();) {
        TriggerListener listener = (TriggerListener) iter.next();
        listener.triggerMisfired(trigger);
    }
}
 
Example #27
Source File: RemoteScheduler.java    From AsuraFramework with 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);
    }
}
 
Example #28
Source File: SingleShotListener.java    From uyuni with 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 File: ScheduleService.java    From elasticsearch-quartz with 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 #30
Source File: JobStoreSupport.java    From AsuraFramework with 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);
            }
        });
}