Java Code Examples for org.quartz.Scheduler#getJobDetail()

The following examples show how to use org.quartz.Scheduler#getJobDetail() . 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: JobServiceImpl.java    From griffin with Apache License 2.0 8 votes vote down vote up
private JobDetail addJobDetail(TriggerKey triggerKey, AbstractJob job)
    throws SchedulerException {
    Scheduler scheduler = factory.getScheduler();
    JobKey jobKey = jobKey(triggerKey.getName(), triggerKey.getGroup());
    JobDetail jobDetail;
    Boolean isJobKeyExist = scheduler.checkExists(jobKey);
    if (isJobKeyExist) {
        jobDetail = scheduler.getJobDetail(jobKey);
    } else {
        jobDetail = newJob(JobInstance.class).storeDurably().withIdentity
            (jobKey).build();
    }
    setJobDataMap(jobDetail, job);
    scheduler.addJob(jobDetail, isJobKeyExist);
    return jobDetail;
}
 
Example 2
Source File: ScheduleServiceImpl.java    From fixflow with Apache License 2.0 6 votes vote down vote up
public List<JobDetail> getJobList(String queryId){
	if(!getIsEnabled()){
		throw new FixFlowScheduleException(ExceptionCode.QUARZTEXCEPTION_ISENABLE);
	}
	Scheduler scheduler = getScheduler();
	List<JobDetail> jobList = new ArrayList<JobDetail>();
	Set<JobKey> set = new HashSet<JobKey>();
	try {
		//如果queryId不为空,则返回queryId对应的job,否则返回所有job
		if(StringUtil.isNotEmpty(queryId)){
			set = scheduler.getJobKeys(GroupMatcher.jobGroupContains(queryId));
		}else{
			List<String> groupNames = scheduler.getJobGroupNames();
			for(String groupName:groupNames){
				set.addAll(scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName)));
			}
		}
		for(JobKey key :set){
			JobDetail job = scheduler.getJobDetail(key); 
			jobList.add(job);
		}
	}catch (SchedulerException e) {
			throw new FixFlowException(e.getMessage(),e);
		}
	return jobList;
}
 
Example 3
Source File: JobInstance.java    From griffin with Apache License 2.0 6 votes vote down vote up
private JobDetail addJobDetail(TriggerKey tk, String pJobName)
    throws SchedulerException, IOException {
    Scheduler scheduler = factory.getScheduler();
    JobKey jobKey = jobKey(tk.getName(), tk.getGroup());
    JobDetail jobDetail;
    Boolean isJobKeyExist = scheduler.checkExists(jobKey);
    if (isJobKeyExist) {
        jobDetail = scheduler.getJobDetail(jobKey);
    } else {
        jobDetail = newJob(SparkSubmitJob.class)
            .storeDurably()
            .withIdentity(jobKey)
            .build();
    }
    setJobDataMap(jobDetail, pJobName);
    scheduler.addJob(jobDetail, isJobKeyExist);
    return jobDetail;
}
 
Example 4
Source File: QuartzQueueAction.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Override
public ActionMessages establishRequiredState(HttpServletRequest request, ActionForm form) throws Exception {
    if ("moveToRouteQueue".equals(request.getParameter("methodToCall")) && request.getAttribute(RENDER_LIST_OVERRIDE) == null) {
        return null;
    }

    Scheduler scheduler = KSBServiceLocator.getScheduler();
    List<QuartzQueueForm> jobs = new ArrayList<QuartzQueueForm>();
    List<String> jobGroups = KSBServiceLocator.getScheduler().getJobGroupNames();

    for (int i = 0; i < jobGroups.size(); i++) {
        String jobGroup = KSBServiceLocator.getScheduler().getJobGroupNames().get(i);
        for(JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(jobGroup))) {
            Trigger trigger = scheduler.getTriggersOfJob(jobKey).get(0);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            jobs.add(new QuartzQueueForm(jobDetail, trigger) );
        }
    }

    request.setAttribute("jobs", jobs);
    return null;
}
 
Example 5
Source File: Quartz2Adapter.java    From javamelody with Apache License 2.0 6 votes vote down vote up
@Override
List<JobDetail> getAllJobsOfScheduler(Scheduler scheduler) throws SchedulerException {
	final List<JobDetail> result = new ArrayList<JobDetail>();
	for (final String jobGroupName : scheduler.getJobGroupNames()) {
		final GroupMatcher<JobKey> groupMatcher = GroupMatcher.groupEquals(jobGroupName);
		for (final JobKey jobKey : scheduler.getJobKeys(groupMatcher)) {
			final JobDetail jobDetail;
			try {
				jobDetail = scheduler.getJobDetail(jobKey);
				// le job peut être terminé et supprimé depuis la ligne ci-dessus
				if (jobDetail != null) {
					result.add(jobDetail);
				}
			} catch (final Exception e) {
				// si les jobs sont persistés en base de données, il peut y avoir une exception
				// dans getJobDetail, par exemple si la classe du job n'existe plus dans l'application
				LOG.debug(e.toString(), e);
			}
		}
	}
	return result;
}
 
Example 6
Source File: QuartzAdapter.java    From javamelody with Apache License 2.0 6 votes vote down vote up
List<JobDetail> getAllJobsOfScheduler(Scheduler scheduler) throws SchedulerException {
	final List<JobDetail> result = new ArrayList<JobDetail>();
	for (final String jobGroupName : scheduler.getJobGroupNames()) {
		for (final String jobName : scheduler.getJobNames(jobGroupName)) {
			final JobDetail jobDetail;
			try {
				jobDetail = scheduler.getJobDetail(jobName, jobGroupName);
				// le job peut être terminé et supprimé depuis la ligne ci-dessus
				if (jobDetail != null) {
					result.add(jobDetail);
				}
			} catch (final Exception e) {
				// si les jobs sont persistés en base de données, il peut y avoir une exception
				// dans getJobDetail, par exemple si la classe du job n'existe plus dans l'application
				LOG.debug(e.toString(), e);
			}
		}
	}
	return result;
}
 
Example 7
Source File: ScheduleJobService.java    From springboot-quartz with MIT License 6 votes vote down vote up
private void wrapScheduleJob(ScheduleJob scheduleJob,Scheduler scheduler,JobKey jobKey,Trigger trigger){  
    try {  
        scheduleJob.setJobName(jobKey.getName());  
        scheduleJob.setJobGroup(jobKey.getGroup()); 
  
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);  
        ScheduleJob job = (ScheduleJob)jobDetail.getJobDataMap().get("scheduleJob");  
        scheduleJob.setDesc(job.getDesc());  
        scheduleJob.setJobId(job.getJobId());
  
        Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());  
        scheduleJob.setJobStatus(triggerState.name());  
        if(trigger instanceof CronTrigger){  
            CronTrigger cronTrigger = (CronTrigger)trigger;  
            String cronExpression = cronTrigger.getCronExpression();  
            scheduleJob.setCronExpression(cronExpression);  
        }  
    } catch (SchedulerException e) {  
        e.printStackTrace(); 
    }  
}
 
Example 8
Source File: QuartzUtil.java    From fixflow with Apache License 2.0 5 votes vote down vote up
/**
 * 根据定时任务和作业名称得到作业
 * @param scheduler 定时任务
 * @param jobKey 作业名称
 * @return
 */
public static JobDetail getJobDetail(Scheduler scheduler, String jobKey) {
	JobDetail jobDetail = null;
	try {
		jobDetail = scheduler.getJobDetail(new JobKey(jobKey));
	} catch (SchedulerException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return jobDetail;
}
 
Example 9
Source File: JobTrigger.java    From spring-cloud-shop with MIT License 5 votes vote down vote up
/**
 * 更新定时任务
 *
 * @param scheduler      the scheduler
 * @param jobName        the job name
 * @param jobGroup       the job group
 * @param cronExpression the cron expression
 * @param param          the param
 */
private static void updateJob(Scheduler scheduler, String jobName, String jobGroup, String cronExpression, Object param) throws SchedulerException {

    // 同步或异步
    Class<? extends Job> jobClass = JobQuartzJobBean.class;
    JobDetail jobDetail = scheduler.getJobDetail(getJobKey(jobName, jobGroup));

    jobDetail = jobDetail.getJobBuilder().ofType(jobClass).build();

    // 更新参数 实际测试中发现无法更新
    JobDataMap jobDataMap = jobDetail.getJobDataMap();
    jobDataMap.put("JobAdapter", param);
    jobDetail.getJobBuilder().usingJobData(jobDataMap);

    TriggerKey triggerKey = getTriggerKey(jobName, jobGroup);

    // 表达式调度构建器
    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

    CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

    // 按新的cronExpression表达式重新构建trigger
    trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
    Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
    // 忽略状态为PAUSED的任务,解决集群环境中在其他机器设置定时任务为PAUSED状态后,集群环境启动另一台主机时定时任务全被唤醒的bug
    if (!JobEnums.PAUSE.name().equalsIgnoreCase(triggerState.name())) {
        // 按新的trigger重新设置job执行
        scheduler.rescheduleJob(triggerKey, trigger);
    }
}
 
Example 10
Source File: SchedulerServiceImplTest.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void scheduleJob(String groupName, String jobName, int startStep, int endStep, Date startTime, String requestorEmailAddress, Map<String,String> additionalJobData ) {
    Scheduler scheduler = (Scheduler) SpringContext.getService("scheduler");
    try {
        JobDetail jobDetail = scheduler.getJobDetail(jobName, groupName);
        if ( jobDetail == null ) {
            fail( "Unable to retrieve JobDetail object for " + groupName + " : " + jobName );
        }
        if ( jobDetail.getJobDataMap() == null ) {
            jobDetail.setJobDataMap( new JobDataMap() );
        }
        jobDetail.getJobDataMap().put(SchedulerService.JOB_STATUS_PARAMETER, SchedulerService.SCHEDULED_JOB_STATUS_CODE);
        scheduler.addJob(jobDetail, true);

        SimpleTriggerDescriptor trigger = new SimpleTriggerDescriptor(jobName+startTime, groupName, jobName, SpringContext.getBean(DateTimeService.class));
        trigger.setStartTime(startTime);
        Trigger qTrigger = trigger.getTrigger();
        qTrigger.getJobDataMap().put(JobListener.REQUESTOR_EMAIL_ADDRESS_KEY, requestorEmailAddress);
        qTrigger.getJobDataMap().put(Job.JOB_RUN_START_STEP, String.valueOf(startStep));
        qTrigger.getJobDataMap().put(Job.JOB_RUN_END_STEP, String.valueOf(endStep));
        if ( additionalJobData != null ) {
            qTrigger.getJobDataMap().putAll(additionalJobData);
        }
        scheduler.scheduleJob(qTrigger);
    }
    catch (SchedulerException e) {
        throw new RuntimeException("Caught exception while scheduling job: " + jobName, e);
    }
}
 
Example 11
Source File: SchedulerServiceSupplier.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Exist job definition.
 * 
 * @param jobName the job name
 * @param jobGroup the job group
 * 
 * @return the string
 */
public   String existJobDefinition(String jobName, String jobGroup) {
	StringBuffer buffer = new StringBuffer("<JOB_EXISTANCE  ");
	try{
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
		if (jobName == null || jobName.trim().equals("")) {
			SpagoBITracer.critical(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), 
								   "existJobDefinition", "Missing job name request parameter!");
			throw new Exception("Missing job name request parameter!");
		}
		if (jobGroup == null || jobGroup.trim().equals("")) {
			SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), 
								"existJobDefinition", "Missing job group name! Using default group...");
			jobGroup = Scheduler.DEFAULT_GROUP;
		}
		JobDetail aJob = scheduler.getJobDetail(jobName, jobGroup);
		if (aJob == null) {
			buffer.append(" exists=\"false\" />");
		} else {
			buffer.append(" exists=\"true\" />");
		}
	} catch (Exception e) {
		SpagoBITracer.critical(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), 
				   			  "existJobDefinition", "Error while checking existence of job", e);
		buffer = new StringBuffer("<JOB_EXISTANCE/> ");
	}
	return buffer.toString();
}
 
Example 12
Source File: SchedulerServiceSupplier.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the job definition.
 * 
 * @param jobName the job name
 * @param jobGroup the job group
 * 
 * @return the job definition
 */
public   String getJobDefinition(String jobName, String jobGroup) {
	String jobStr = "";
	try{
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
		if (jobName == null || jobName.trim().equals("")) {
			SpagoBITracer.critical(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), 
								   "getJobDefinition", "Missing job name request parameter!");
			throw new Exception("Missing job name request parameter!");
		}
		if (jobGroup == null || jobGroup.trim().equals("")) {
			SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), 
								"getJobDefinition", "Missing job group name! Using default group...");
			jobGroup = Scheduler.DEFAULT_GROUP;
		}
		JobDetail aJob = scheduler.getJobDetail(jobName, jobGroup);
		if (aJob == null) {
			SpagoBITracer.critical(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), "getJobDefinition", 
								   "Job with name '" + jobName + "' not found in group '" + jobGroup + "'!");
			throw new Exception("Job with name '" + jobName + "' not found in group '" + jobGroup + "'!");
		}
		jobStr = serializeJobDetail(aJob);
	} catch (Exception e) {
		SpagoBITracer.critical(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), 
				   			   "getJobDefinition", "Error while recovering job definition");
	}
	return jobStr;
}
 
Example 13
Source File: SchedulerServiceSupplier.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the job list.
 * 
 * @return the job list
 */
public String getJobList() {
	String xml = "";
	try {
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); 
		List toReturn = new ArrayList();
		String[] groups = scheduler.getJobGroupNames();
		if (groups == null || groups.length == 0) {
			SpagoBITracer.warning(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), 
					              "getJobList", "No job groups defined!");
		} else {
			for (int i = 0; i < groups.length; i++) {
				String group = groups[i];
				String[] jobNames = scheduler.getJobNames(group);
				if (jobNames == null || jobNames.length == 0) {
					SpagoBITracer.warning(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), 
							              "getJobList", "No job defined for group " + group + "!");
				} else {
					for (int j = 0; j < jobNames.length; j++) {
						JobDetail aJob = scheduler.getJobDetail(jobNames[j], group);
						toReturn.add(aJob);
					}
				}
			}
		}
		xml = buildJobListXmlString(toReturn);
	} catch (Exception e) {
		SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, this.getClass().getName(), 
	              			"getJobList", "Error while recovering job list");
		xml = "<ROWS></ROWS>";
	}
	return xml;
}
 
Example 14
Source File: JobServiceImpl.java    From spring-boot-quartz-demo with MIT License 5 votes vote down vote up
/**
 * Get the current state of job
 */
public String getJobState(String jobName) {
	System.out.println("JobServiceImpl.getJobState()");

	try {
		String groupKey = "SampleGroup";
		JobKey jobKey = new JobKey(jobName, groupKey);

		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		JobDetail jobDetail = scheduler.getJobDetail(jobKey);

		List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobDetail.getKey());
		if(triggers != null && triggers.size() > 0){
			for (Trigger trigger : triggers) {
				TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());

				if (TriggerState.PAUSED.equals(triggerState)) {
					return "PAUSED";
				}else if (TriggerState.BLOCKED.equals(triggerState)) {
					return "BLOCKED";
				}else if (TriggerState.COMPLETE.equals(triggerState)) {
					return "COMPLETE";
				}else if (TriggerState.ERROR.equals(triggerState)) {
					return "ERROR";
				}else if (TriggerState.NONE.equals(triggerState)) {
					return "NONE";
				}else if (TriggerState.NORMAL.equals(triggerState)) {
					return "SCHEDULED";
				}
			}
		}
	} catch (SchedulerException e) {
		System.out.println("SchedulerException while checking job with name and group exist:"+e.getMessage());
		e.printStackTrace();
	}
	return null;
}
 
Example 15
Source File: QuartzUtils.java    From quartz-web with Apache License 2.0 5 votes vote down vote up
/**
 * 获取scheduler下所有的jobDetail
 * @param scheduler
 * @return
 * @throws SchedulerException
 */
public static List<JobDetail> getAllJobsOfScheduler(Scheduler scheduler) throws SchedulerException {
    List<JobDetail> result = new ArrayList<JobDetail>();
    List<String> jobGroupNames = scheduler.getJobGroupNames();
    for (String groupName : jobGroupNames) {
        Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.<JobKey>groupEquals(groupName));
        for (JobKey jobKey : jobKeys) {
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            result.add(jobDetail);
        }
    }
    return result;
}
 
Example 16
Source File: SchedulerAdapter.java    From iaf with Apache License 2.0 4 votes vote down vote up
/**
 * Get all jobgroups, jobs within this group, the jobdetail and the
 * associated triggers in XML format.
 */
public XmlBuilder getJobGroupNamesWithJobsToXml(Scheduler theScheduler, IbisManager ibisManager) {
	XmlBuilder xbRoot = new XmlBuilder("jobGroups");

	try {
		// process groups
		List<String> jgnames = theScheduler.getJobGroupNames();

		for (int i = 0; i < jgnames.size(); i++) {
			XmlBuilder el = new XmlBuilder("jobGroup");
			String jobGroupName = jgnames.get(i);
			el.addAttribute("name", jobGroupName);

			// process jobs within group
			XmlBuilder jb = new XmlBuilder("jobs");
			Set<JobKey> jobKeys = theScheduler.getJobKeys(GroupMatcher.jobGroupEquals(jobGroupName));

			for (JobKey jobKey : jobKeys) {
				XmlBuilder jn = new XmlBuilder("job");
				String jobName = jobKey.getName();
				jn.addAttribute("name", jobName);

				// details for job
				JobDetail jobDetail = theScheduler.getJobDetail(jobKey);
				XmlBuilder jd = jobDetailToXmlBuilder(jobDetail);
				jn.addSubElement(jd);

				// get the triggers for this job
				List<? extends Trigger> triggers = theScheduler.getTriggersOfJob(jobKey);
				XmlBuilder tr = getJobTriggers(triggers);
				jn.addSubElement(tr);


				JobDataMap jobDataMap = jobDetail.getJobDataMap();
				XmlBuilder datamap = jobDataMapToXmlBuilder(jobDataMap);
				jn.addSubElement(datamap);
				jb.addSubElement(jn);

				JobDef jobDef = null;
				if(ibisManager != null) {
					for (Configuration configuration : ibisManager.getConfigurations()) {
						jobDef = configuration.getScheduledJob(jobName);
						if (jobDef != null) {
							break;
						}
					}
				}
				XmlBuilder ms = getJobMessages(jobDef);
				jn.addSubElement(ms);
				XmlBuilder jrs= getJobRunStatistics(jobDef);
				jn.addSubElement(jrs);
			}
			el.addSubElement(jb);
			xbRoot.addSubElement(el);
		}
	} catch (SchedulerException se) {
		log.error(se);
	}

	return xbRoot;
}
 
Example 17
Source File: ShowScheduler.java    From iaf with Apache License 2.0 4 votes vote down vote up
private Map<String, Object> getJobData(JobKey jobKey, boolean expanded) throws SchedulerException {
	Map<String, Object> jobData = new HashMap<String, Object>();
	Scheduler scheduler = getScheduler();
	String jobName = jobKey.getName();
	JobDetail job = scheduler.getJobDetail(jobKey);

	jobData.put("fullName", job.getKey().getGroup() + "." + job.getKey().getName());
	jobData.put("name", job.getKey().getName());
	jobData.put("group", job.getKey().getGroup());
	String description = "-";
	if (StringUtils.isNotEmpty(job.getDescription()))
		description = job.getDescription();
	jobData.put("description", description);
	jobData.put("stateful", job.isPersistJobDataAfterExecution() && job.isConcurrentExectionDisallowed());
	jobData.put("durable",job.isDurable());
	jobData.put("jobClass", job.getJobClass().getSimpleName());

	if(job instanceof IbisJobDetail) {
		jobData.put("type", ((IbisJobDetail) job).getJobType());
	}

	TriggerState state = scheduler.getTriggerState(TriggerKey.triggerKey(jobName, jobKey.getGroup()));
	jobData.put("state", state.name());

	jobData.put("triggers", getJobTriggers(scheduler.getTriggersOfJob(jobKey)));
	jobData.put("messages", getJobMessages(job));

	JobDataMap jobMap = job.getJobDataMap();
	jobData.put("properties", getJobData(jobMap));

	if(expanded) {
		JobDef jobDef = (JobDef) jobMap.get(ConfiguredJob.JOBDEF_KEY);
		jobData.put("adapter", jobDef.getAdapterName());
		jobData.put("receiver", jobDef.getReceiverName());
		jobData.put("message", jobDef.getMessage());
		
		Locker locker = jobDef.getLocker();
		if(locker != null) {
			jobData.put("locker", true);
			jobData.put("lockkey", locker.getObjectId());
		} else {
			jobData.put("locker", false);
		}
	}

	return jobData;
}
 
Example 18
Source File: QuartzUtils.java    From quartz-web with Apache License 2.0 2 votes vote down vote up
/**
 * 获取job信息
 * @param scheduler
 * @param jobName
 * @param jobGroup
 * @return
 * @throws SchedulerException
 */
public static JobDetail getJob(Scheduler scheduler, String jobName, String jobGroup) throws SchedulerException {
    JobKey jobKey = getJobKey(jobName, jobGroup);
    JobDetail jobDetail = scheduler.getJobDetail(jobKey);
    return jobDetail;
}