Java Code Examples for org.quartz.JobDetail#getKey()

The following examples show how to use org.quartz.JobDetail#getKey() . 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: CronService.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
public void cancel(JobDetail jd) {

		if (jd == null) {
			return;
		}

		if (jd.getKey() == null) {
			throw new CronServiceException("JobDetail should have JobKey");
		}

		try {
			scheduler.deleteJob(jd.getKey());
		} catch (SchedulerException e) {
			throw new CronServiceException("Failed to delete Job", e);
		}
	}
 
Example 2
Source File: FHTBinding.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * The user may configure this binding to update the internal clock of
 * FHT80b devices via rf command. The method takes care of scheduling this
 * job.
 */
private JobKey scheduleJob(Class<? extends Job> jobClass, String cronExpression) {
    JobKey jobKey = null;
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
        JobDetail detail = JobBuilder.newJob(jobClass).withIdentity("FHT " + jobClass.getSimpleName(), "cul")
                .build();
        detail.getJobDataMap().put(FHTBinding.class.getName(), this);

        CronTrigger trigger = TriggerBuilder.newTrigger().forJob(detail)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();
        jobKey = detail.getKey();
        sched.scheduleJob(detail, trigger);
    } catch (SchedulerException e) {
        logger.error("Can't schedule time update job", e);
    }
    return jobKey;
}
 
Example 3
Source File: ConfigScheduler.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
private synchronized void schedule()
{
    try
    {
        scheduler = schedulerFactory.getScheduler();

        JobDetail job = JobBuilder.newJob()
                .withIdentity(jobName)
                .ofType(ConfigSchedulerJob.class)
                .build();
        jobKey = job.getKey();
        job.getJobDataMap().put(CONFIG_SCHEDULER, this);
        CronExpression cronExpression = normalCronSchedule ? this.cronExpression : initialAndOnErrorCronExpression;
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName+"Trigger", Scheduler.DEFAULT_GROUP)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .build();
        scheduler.startDelayed(0);
        scheduler.scheduleJob(job, trigger);
        log.debug("Schedule set "+cronExpression);
    }
    catch (Exception e)
    {
        log.error("Error scheduling "+e.getMessage());
    }
}
 
Example 4
Source File: JobDetailImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean equals(Object obj) {
    if (!(obj instanceof JobDetail)) {
        return false;
    }

    JobDetail other = (JobDetail) obj;

    if(other.getKey() == null || getKey() == null)
        return false;
    
    if (!other.getKey().equals(getKey())) {
        return false;
    }
        
    return true;
}
 
Example 5
Source File: SchedulerUtil.java    From SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 执行计划任务
 * @param job
 * @param trigger
 * @return
 * @throws SchedulerException
 */
public static ScheduleJobResult executeScheduleJob(JobDetail job, Trigger trigger) throws SchedulerException {
    ScheduleJobResult scheduleJobResult = new ScheduleJobResult();
    //判断是否满足计划任务的创建条件
    if(job.getKey() == null || trigger.getKey() == null || job.getJobDataMap() == null){
        scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.FAILED);
        //不满足计划任务的创建条件,返回scheduleJobResult值类
        return scheduleJobResult;
    }
    scheduleJobResult.setJobDetail(job);
    scheduleJobResult.setTrigger(trigger);
    //开始分配计划任务
    Scheduler scheduler  = SchedulerFactory.getScheduler();
    //开始判断是否存在相同的计划任务
    if(scheduler.checkExists(job.getKey())){
        log.info("存在相同的计划任务:{}",job.getKey());
        scheduler.deleteJob(job.getKey());
        scheduleJobResult.setJobKey(job.getKey());
        scheduleJobResult.setTriggerKey(trigger.getKey());
        scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.ISEXIST);
        scheduler.scheduleJob(job,trigger);
        scheduler.start();
    }else{
        scheduler.scheduleJob(job,trigger);
        scheduler.start();
        scheduleJobResult.setJobKey(job.getKey());
        scheduleJobResult.setTriggerKey(trigger.getKey());
        scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.SUCCESS);
    }
    //计划任务分配成功
    return scheduleJobResult;
}
 
Example 6
Source File: JobInstance.java    From griffin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void setJobStartTime(JobDetail jobDetail)
    throws SchedulerException {
    Scheduler scheduler = factory.getScheduler();
    JobKey jobKey = jobDetail.getKey();
    List<Trigger> triggers =
        (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
    Date triggerTime = triggers.get(0).getPreviousFireTime();
    jobStartTime = triggerTime.getTime();
}
 
Example 7
Source File: QuartzScheduler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Interrupt all instances of the identified InterruptableJob executing in 
 * this Scheduler instance.
 *  
 * <p>
 * This method is not cluster aware.  That is, it will only interrupt 
 * instances of the identified InterruptableJob currently executing in this 
 * Scheduler instance, not across the entire cluster.
 * </p>
 * 
 * @see org.quartz.core.RemotableQuartzScheduler#interrupt(JobKey)
 */
public boolean interrupt(JobKey jobKey) throws UnableToInterruptJobException {

    List<JobExecutionContext> jobs = getCurrentlyExecutingJobs();
    
    JobDetail jobDetail = null;
    Job job = null;
    
    boolean interrupted = false;
    
    for(JobExecutionContext jec : jobs) {
        jobDetail = jec.getJobDetail();
        if (jobKey.equals(jobDetail.getKey())) {
            job = jec.getJobInstance();
            if (job instanceof InterruptableJob) {
                ((InterruptableJob)job).interrupt();
                interrupted = true;
            } else {
                throw new UnableToInterruptJobException(
                        "Job " + jobDetail.getKey() +
                        " can not be interrupted, since it does not implement " +                        
                        InterruptableJob.class.getName());
            }
        }                        
    }
    
    return interrupted;
}
 
Example 8
Source File: JobParamsDetail.java    From spring-batch-rest with Apache License 2.0 5 votes vote down vote up
public JobParamsDetail(JobDetail jobDetail) {

		this.setJobClass(jobDetail.getJobClass());
		this.setDescription(jobDetail.getDescription());
		if (jobDetail.getKey() == null)
			this.setKey(new JobKey(Key.createUniqueName(null), null));
		this.setKey(jobDetail.getKey());
		this.setDurability(jobDetail.isDurable());
		this.setRequestsRecovery(jobDetail.requestsRecovery());

		if (!jobDetail.getJobDataMap().isEmpty())
			this.setJobDataMap(jobDetail.getJobDataMap());
	}
 
Example 9
Source File: ScheduleJobService.java    From springboot-quartz with MIT License 5 votes vote down vote up
public List<ScheduleJob> getRunningJobList() throws SchedulerException{  
    List<JobExecutionContext> executingJobList = scheduler.getCurrentlyExecutingJobs();  
    List<ScheduleJob> jobList = new ArrayList<>(executingJobList.size());  
    for(JobExecutionContext executingJob : executingJobList){  
        ScheduleJob scheduleJob = new ScheduleJob();  
        JobDetail jobDetail = executingJob.getJobDetail();  
        JobKey jobKey = jobDetail.getKey();  
        Trigger trigger = executingJob.getTrigger();  
        this.wrapScheduleJob(scheduleJob,scheduler,jobKey,trigger);  
        jobList.add(scheduleJob);  
    }  
    return jobList;  
}
 
Example 10
Source File: SchedulerUtil.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 执行计划任务
 * @param job
 * @param trigger
 * @return
 * @throws SchedulerException
 */
public static ScheduleJobResult executeScheduleJob(JobDetail job, Trigger trigger) throws SchedulerException {
    ScheduleJobResult scheduleJobResult = new ScheduleJobResult();
    //判断是否满足计划任务的创建条件
    if(job.getKey() == null || trigger.getKey() == null || job.getJobDataMap() == null){
        scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.FAILED);
        //不满足计划任务的创建条件,返回scheduleJobResult值类
        return scheduleJobResult;
    }
    scheduleJobResult.setJobDetail(job);
    scheduleJobResult.setTrigger(trigger);
    //开始分配计划任务
    Scheduler scheduler  = SchedulerFactory.getScheduler();
    //开始判断是否存在相同的计划任务
    if(scheduler.checkExists(job.getKey())){
        log.info("存在相同的计划任务:{}",job.getKey());
        scheduler.deleteJob(job.getKey());
        scheduleJobResult.setJobKey(job.getKey());
        scheduleJobResult.setTriggerKey(trigger.getKey());
        scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.ISEXIST);
        scheduler.scheduleJob(job,trigger);
        scheduler.start();
    }else{
        scheduler.scheduleJob(job,trigger);
        scheduler.start();
        scheduleJobResult.setJobKey(job.getKey());
        scheduleJobResult.setTriggerKey(trigger.getKey());
        scheduleJobResult.setScheduleJobStatus(ScheduleJobStatus.SUCCESS);
    }
    //计划任务分配成功
    return scheduleJobResult;
}
 
Example 11
Source File: JobStoreImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Helper to update all triggers for a job (except the fired trigger)
 * which are WAITING/PAUSED to BLOCKED/PAUSE_BLOCKED state.
 *
 * @see #triggersFired
 */
private void blockTriggers(final ODatabaseDocumentTx db,
                           final TriggerKey firedTriggerKey,
                           final JobDetail jobDetail)
{
  JobKey jobKey = jobDetail.getKey();

  log.trace("Blocking other triggers: firedTriggerKey={}, jobKey={}", firedTriggerKey, jobKey);

  Iterable<TriggerEntity> matches = triggerEntityAdapter.browseWithPredicate
      (db, input -> {
        switch (input.getState()) {
          case WAITING:
          case PAUSED:
            return jobKey.equals(input.getValue().getJobKey());
        }
        return false;
      });

  if (isMultiNodeTask(jobDetail)) {
    matches = local(matches); // multinode task; each node only needs to block local triggers
  }

  for (TriggerEntity entity : matches) {
    if (entity.getState() == PAUSED) {
      entity.setState(PAUSED_BLOCKED);
    }
    else {
      entity.setState(BLOCKED);
    }
    triggerEntityAdapter.editEntity(db, entity);
  }
}
 
Example 12
Source File: JobStoreImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Helper to update all triggers for a job which are BLOCKED/PAUSED_BLOCKED to WAITING/PAUSED state.
 *
 * @see #triggeredJobComplete
 */
private void unblockTriggers(final ODatabaseDocumentTx db, final JobDetail jobDetail) {
  JobKey jobKey = jobDetail.getKey();

  log.trace("Unblock triggers: jobKey={}", jobKey);

  Iterable<TriggerEntity> matches = triggerEntityAdapter.browseWithPredicate
      (db, input -> {
        switch (input.getState()) {
          case BLOCKED:
          case PAUSED_BLOCKED:
            return jobKey.equals(input.getValue().getJobKey());
        }
        return false;
      });

  if (isMultiNodeTask(jobDetail)) {
    matches = local(matches); // multinode task; each node only needs to unblock local triggers
  }

  for (TriggerEntity entity : matches) {
    if (entity.getState() == PAUSED_BLOCKED) {
      entity.setState(PAUSED);
    }
    else {
      entity.setState(WAITING);
    }
    triggerEntityAdapter.editEntity(db, entity);
  }
}
 
Example 13
Source File: JobDetailEntity.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Populate entity fields used for indexing.
 */
@Override
public void setValue(final JobDetail value) {
  super.setValue(value);

  JobKey key = value.getKey();
  checkState(key != null, "Missing key");
  setName(key.getName());
  setGroup(key.getGroup());

  Class clazz = value.getJobClass();
  checkState(clazz != null, "Missing job-class");
  setJobType(clazz.getCanonicalName());
}
 
Example 14
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 15
Source File: QuartzSchedulerSPI.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a stub of a {@link QuartzTaskJobListener} attached to the job with scheduling unset.
 * See NEXUS-18983
 */
private QuartzTaskJobListener stubJobListener(final JobDetail jobDetail) throws SchedulerException {
  log.debug("Stubbing task-state: jobDetail={}", jobDetail);

  TaskConfiguration taskConfiguration = configurationOf(jobDetail);
  Schedule schedule = scheduleFactory.manual();
  QuartzTaskState taskState = new QuartzTaskState(taskConfiguration, schedule, null);

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

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

  return listener;
}
 
Example 16
Source File: SchedulerTestBase.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceJobDetail() throws SchedulerException, ParseException {
	JobDetail job = createServiceJob("test1");
	assertNotNull(job);

	JobKey details = job.getKey();
	assertEquals("test1", details.getName());
	assertEquals(SchedulerHelper.DEFAULT_GROUP, details.getGroup());

	assertEquals(3, job.getJobDataMap().size());
}
 
Example 17
Source File: SchedulerTestBase.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfiguredJobDetail() throws SchedulerException, ParseException {
	JobDetail job = createConfiguredJob("test2");
	assertNotNull(job);

	JobKey details = job.getKey();
	assertEquals("test2", details.getName());
	assertEquals(SchedulerHelper.DEFAULT_GROUP, details.getGroup());

	assertEquals(2, job.getJobDataMap().size());
}
 
Example 18
Source File: RAMJobStore.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
JobWrapper(JobDetail jobDetail) {
    this.jobDetail = jobDetail;
    key = jobDetail.getKey();
}
 
Example 19
Source File: QuartzScheduler.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * <p>
 * Add the <code>{@link org.quartz.Job}</code> identified by the given
 * <code>{@link org.quartz.JobDetail}</code> to the Scheduler, and
 * associate the given <code>{@link org.quartz.Trigger}</code> with it.
 * </p>
 * 
 * <p>
 * If the given Trigger does not reference any <code>Job</code>, then it
 * will be set to reference the Job passed with it into this method.
 * </p>
 * 
 * @throws SchedulerException
 *           if the Job or Trigger cannot be added to the Scheduler, or
 *           there is an internal Scheduler error.
 */
public Date scheduleJob(JobDetail jobDetail,
        Trigger trigger) throws SchedulerException {
    validateState();

    if (jobDetail == null) {
        throw new SchedulerException("JobDetail cannot be null");
    }
    
    if (trigger == null) {
        throw new SchedulerException("Trigger cannot be null");
    }
    
    if (jobDetail.getKey() == null) {
        throw new SchedulerException("Job's key cannot be null");
    }

    if (jobDetail.getJobClass() == null) {
        throw new SchedulerException("Job's class cannot be null");
    }
    
    OperableTrigger trig = (OperableTrigger)trigger;

    if (trigger.getJobKey() == null) {
        trig.setJobKey(jobDetail.getKey());
    } else if (!trigger.getJobKey().equals(jobDetail.getKey())) {
        throw new SchedulerException(
            "Trigger does not reference given job!");
    }

    trig.validate();

    Calendar cal = null;
    if (trigger.getCalendarName() != null) {
        cal = resources.getJobStore().retrieveCalendar(trigger.getCalendarName());
    }
    Date ft = trig.computeFirstFireTime(cal);

    if (ft == null) {
        throw new SchedulerException(
                "Based on configured schedule, the given trigger '" + trigger.getKey() + "' will never fire.");
    }

    resources.getJobStore().storeJobAndTrigger(jobDetail, trig);
    notifySchedulerListenersJobAdded(jobDetail);
    notifySchedulerThread(trigger.getNextFireTime().getTime());
    notifySchedulerListenersSchduled(trigger);

    return ft;
}
 
Example 20
Source File: QuartzTask.java    From smart-admin with MIT License 4 votes vote down vote up
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    JobDetail jobDetail = context.getJobDetail();
    Object params = jobDetail.getJobDataMap().get(QuartzConst.QUARTZ_PARAMS_KEY);
    JobKey jobKey = jobDetail.getKey();

    Long taskId = SmartQuartzUtil.getTaskIdByJobKey(jobKey);
    QuartzTaskService quartzTaskService = (QuartzTaskService) SmartApplicationContext.getBean("quartzTaskService");
    QuartzTaskEntity quartzTaskEntity = quartzTaskService.getByTaskId(taskId);

    QuartzTaskLogService quartzTaskLogService = (QuartzTaskLogService) SmartApplicationContext.getBean("quartzTaskLogService");

    QuartzTaskLogEntity taskLogEntity = new QuartzTaskLogEntity();
    taskLogEntity.setTaskId(taskId);
    taskLogEntity.setIpAddress(SmartIPUtil.getLocalHostIP());
    taskLogEntity.setTaskName(quartzTaskEntity.getTaskName());
    String paramsStr = null;
    if (params != null) {
        paramsStr = params.toString();
        taskLogEntity.setTaskParams(paramsStr);
    }
    taskLogEntity.setUpdateTime(new Date());
    taskLogEntity.setCreateTime(new Date());
    //任务开始时间
    long startTime = System.currentTimeMillis();
    try {
        ITask taskClass = (ITask) SmartApplicationContext.getBean(quartzTaskEntity.getTaskBean());
        taskClass.execute(paramsStr);
        taskLogEntity.setProcessStatus(TaskResultEnum.SUCCESS.getStatus());
    } catch (Exception e) {
        log.error("", e);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        taskLogEntity.setProcessStatus(TaskResultEnum.FAIL.getStatus());
        taskLogEntity.setProcessLog(sw.toString());
    } finally {
        long times = System.currentTimeMillis() - startTime;
        taskLogEntity.setProcessDuration(times);
        quartzTaskLogService.save(taskLogEntity);
    }

}