org.quartz.Job Java Examples

The following examples show how to use org.quartz.Job. 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: MockScheduler.java    From smarthome with Eclipse Public License 2.0 13 votes vote down vote up
/**
 * "Run" all of the jobs in the scheduler.
 *
 * NB this is a mock class. We ignore the time that the jobs are
 * actually scheduled for, and just run them all.
 *
 * @throws JobExecutionException
 * @throws IllegalAccessException
 * @throws InstantiationException
 *
 */
public void run() throws JobExecutionException, InstantiationException, IllegalAccessException {
    for (Entry<Trigger, JobExecutionContext> entry : jobs.entrySet()) {
        JobExecutionContext context = entry.getValue();
        try {
            currentlyExecutingJobs.add(context);
            Job job = context.getJobDetail().getJobClass().newInstance();
            job.execute(context);
        } finally {
            currentlyExecutingJobs.remove(context);
            jobs.remove(entry.getKey());
            Trigger newTrigger = rescheduledJobs.remove(context.getTrigger().getKey());
            if (newTrigger != null) {
                jobs.put(newTrigger, context);
            }
        }
    }
}
 
Example #2
Source File: QuartzSchedulerBeanTargetEditor.java    From light-task-scheduler with Apache License 2.0 7 votes vote down vote up
private QuartzJobContext buildQuartzJobContext(QuartzJobContext quartzJobContext, Trigger trigger) {
    JobDataMap triggerJobDataMap = trigger.getJobDataMap();
    JobDetail jobDetail = (JobDetail) triggerJobDataMap.get("jobDetail");
    // 要执行的类
    MethodInvoker methodInvoker = (MethodInvoker) jobDetail.getJobDataMap().get("methodInvoker");
    Map<String, Object> jobDataMap = new HashMap<String, Object>();
    jobDataMap.putAll(triggerJobDataMap);
    jobDataMap.putAll(jobDetail.getJobDataMap());
    jobDataMap.remove("jobDetail");
    jobDataMap.remove("methodInvoker");

    quartzJobContext.setJobDataMap(jobDataMap);
    if (methodInvoker != null) {
        quartzJobContext.setJobExecution(new MethodInvokeJobExecution(methodInvoker));
    } else {
        Class<? extends Job> jobClass = jobDetail.getJobClass();
        try {
            Job job = jobClass.newInstance();
            quartzJobContext.setJobExecution(new JobDetailJobExecution(job));
        } catch (Exception e) {
            throw new QuartzProxyException("Instance JobClass[" + (jobClass == null ? null : jobClass.getName()) + "] error", e);
        }
    }
    return quartzJobContext;
}
 
Example #3
Source File: JobScheduler.java    From openhab1-addons with Eclipse Public License 2.0 7 votes vote down vote up
/**
 * Schedules a job at the specified date/time, deletes a previously
 * scheduled job.
 */
private void schedule(Calendar calendar, String jobName, JobDataMap jobDataMap, Class<? extends Job> jobClass) {
    if (System.currentTimeMillis() < calendar.getTimeInMillis()) {
        try {
            JobKey jobKey = new JobKey(jobName, JOB_GROUP);
            if (scheduler.getJobDetail(jobKey) != null) {
                scheduler.deleteJob(jobKey);
            }
            Trigger trigger = newTrigger().withIdentity(jobName + "-Trigger", JOB_GROUP).startAt(calendar.getTime())
                    .build();
            JobDetail jobDetail = newJob(jobClass).withIdentity(jobKey).usingJobData(jobDataMap).build();
            scheduler.scheduleJob(jobDetail, trigger);
            logger.debug("Scheduled job with name {} at {}", jobName, sdf.format(calendar.getTime()));
        } catch (SchedulerException ex) {
            logger.error(ex.getMessage(), ex);
        }
    } else {
        logger.debug("Skipping job with name {} for today, starttime is in the past", jobName);
    }
}
 
Example #4
Source File: JobExecutionContextImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>
 * Create a JobExcecutionContext with the given context data.
 * </p>
 */
public JobExecutionContextImpl(Scheduler scheduler,
        TriggerFiredBundle firedBundle, Job job) {
    this.scheduler = scheduler;
    this.trigger = firedBundle.getTrigger();
    this.calendar = firedBundle.getCalendar();
    this.jobDetail = firedBundle.getJobDetail();
    this.job = job;
    this.recovering = firedBundle.isRecovering();
    this.fireTime = firedBundle.getFireTime();
    this.scheduledFireTime = firedBundle.getScheduledFireTime();
    this.prevFireTime = firedBundle.getPrevFireTime();
    this.nextFireTime = firedBundle.getNextFireTime();
    
    this.jobDataMap = new JobDataMap();
    this.jobDataMap.putAll(jobDetail.getJobDataMap());
    this.jobDataMap.putAll(trigger.getJobDataMap());
}
 
Example #5
Source File: SimpleJobFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public Job newJob(TriggerFiredBundle bundle, Scheduler Scheduler) throws SchedulerException {

        JobDetail jobDetail = bundle.getJobDetail();
        Class<? extends Job> jobClass = jobDetail.getJobClass();
        try {
            if(log.isDebugEnabled()) {
                log.debug(
                    "Producing instance of Job '" + jobDetail.getKey() + 
                    "', class=" + jobClass.getName());
            }
            
            return jobClass.newInstance();
        } catch (Exception e) {
            SchedulerException se = new SchedulerException(
                    "Problem instantiating class '"
                            + jobDetail.getJobClass().getName() + "'", e);
            throw se;
        }
    }
 
Example #6
Source File: CommonJobBean.java    From dubai with MIT License 6 votes vote down vote up
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    StopWatch stopWatch = new LoggingStopWatch();

    ApplicationContext applicationContext = getApplicationContext(jobExecutionContext);
    String realJobBeanName = getRealJobBeanName(jobExecutionContext);
    Job realJob = (Job) applicationContext.getBean(realJobBeanName);

    try {
        realJob.execute(jobExecutionContext);
    } catch (Exception e) {
        logger.error(String.format("Error happened when execute job, realJobBeanName: %s, jobDataMap:[%s]", realJobBeanName, buildJobDataMap(jobExecutionContext)), e);
    }

    stopWatch.stop(String.format("Job executed, realJobBeanName: %s, jobDataMap:[%s]", realJobBeanName, buildJobDataMap(jobExecutionContext)));
}
 
Example #7
Source File: CdiAwareJobFactory.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException
{
    Job result = null;
    try
    {
        Class<? extends Job> jobClass = bundle.getJobDetail().getJobClass();
        result = BeanProvider.getContextualReference(jobClass);
        scheduler.getContext().put(jobClass.getName(), Boolean.TRUE);
    }
    catch (Exception e)
    {
        if (result == null)
        {
            result = defaultFactory.newJob(bundle, scheduler);
        }
    }
    return result;
}
 
Example #8
Source File: QuartzManagerUtils.java    From kafka-eagle with Apache License 2.0 6 votes vote down vote up
/** Add new job. */
public static void addJob(BaseJobContext jobContext, String jobName, Class<? extends Job> jobClass, String cron) {
	try {
		Scheduler sched = schedulerFactory.getScheduler();
		JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, KE_JOB_GROUP_NAME).build();
		jobDetail.getJobDataMap().put(AlarmQueue.JOB_PARAMS, jobContext);
		TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
		triggerBuilder.withIdentity("ke_trigger_name_" + new Date().getTime(), "ke_trigger_group_" + new Date().getTime());
		triggerBuilder.startNow();
		triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
		CronTrigger trigger = (CronTrigger) triggerBuilder.build();
		sched.scheduleJob(jobDetail, trigger);
		if (!sched.isShutdown()) {
			sched.start();
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #9
Source File: JobDetailSupport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @param cData
 * @return JobDetail
 */
public static JobDetail newJobDetail(CompositeData cData)
  throws ClassNotFoundException
{
    JobDetailImpl jobDetail = new JobDetailImpl();

    int i = 0;
    jobDetail.setName((String) cData.get(ITEM_NAMES[i++]));
    jobDetail.setGroup((String) cData.get(ITEM_NAMES[i++]));
    jobDetail.setDescription((String) cData.get(ITEM_NAMES[i++]));
    Class<?> jobClass = Class.forName((String) cData.get(ITEM_NAMES[i++]));
    @SuppressWarnings("unchecked")
    Class<? extends Job> jobClassTyped = (Class<? extends Job>)jobClass;
    jobDetail.setJobClass(jobClassTyped);
    jobDetail.setJobDataMap(JobDataMapSupport.newJobDataMap((TabularData) cData.get(ITEM_NAMES[i++])));
    jobDetail.setDurability((Boolean) cData.get(ITEM_NAMES[i++]));
    jobDetail.setRequestsRecovery((Boolean) cData.get(ITEM_NAMES[i++]));

    return jobDetail;
}
 
Example #10
Source File: RedisJobStore.java    From redis-quartz with MIT License 6 votes vote down vote up
/**
 * Retrieves job from redis.
 *
 * @param jobKey the job key
 * @param jedis thread-safe redis connection
 * @return the job detail
 * @throws JobPersistenceException
 */
@SuppressWarnings("unchecked")
private JobDetail retrieveJob(JobKey jobKey, Jedis jedis) throws JobPersistenceException, ClassNotFoundException {
	String jobHashkey = createJobHashKey(jobKey.getGroup(), jobKey.getName());
	String jobDataMapHashKey = createJobDataMapHashKey(jobKey.getGroup(), jobKey.getName());
     if (!jedis.exists(jobHashkey)) {
        log.warn("job: " + jobHashkey + " does not exist");
        return null;
     }
	Class<Job> jobClass = (Class<Job>) loadHelper.getClassLoader().loadClass(jedis.hget(jobHashkey, JOB_CLASS));
	JobBuilder jobBuilder = JobBuilder.newJob(jobClass)
								.withIdentity(jobKey)
								.withDescription(jedis.hget(jobHashkey, DESCRIPTION))
								.storeDurably(Boolean.getBoolean(jedis.hget(jobHashkey, IS_DURABLE)));
							
	Set<String> jobDataMapFields = jedis.hkeys(jobDataMapHashKey);
	if (!jobDataMapFields.isEmpty()) {
		for (String jobDataMapField : jobDataMapFields)
			jobBuilder.usingJobData(jobDataMapField, jedis.hget(jobDataMapHashKey, jobDataMapField));							
	}
	
	return jobBuilder.build();		
}
 
Example #11
Source File: AdaptableJobFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException {
	try {
		Object jobObject = createJobInstance(bundle);
		return adaptJob(jobObject);
	}
	catch (Exception ex) {
		throw new SchedulerException("Job instantiation failed", ex);
	}
}
 
Example #12
Source File: Context.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends Job> void scheduleLocal(Class<T> cls, Integer delay, Integer interval) throws Exception {
	JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(cls.getName(), clazz.getName())
			.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);
}
 
Example #13
Source File: Context.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends Job> void scheduleLocal(Class<T> cls) throws Exception {
	/* 需要单独生成一个独立任务,保证group和预约的任务不重复 */
	String group = StringTools.uniqueToken();
	JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(cls.getName(), group).withDescription(Config.node())
			.build();
	/* 经过测试0代表不重复,进运行一次 */
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(cls.getName(), group)
			.withDescription("scheduleLocal")
			.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).withRepeatCount(0))
			.build();
	scheduler.scheduleJob(jobDetail, trigger);
}
 
Example #14
Source File: JobService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private <T> JobDetail buildJobDetail(String sdxId, String crn, Class<? extends Job> clazz) {
    JobDataMap jobDataMap = new JobDataMap();

    jobDataMap.put(LOCAL_ID, sdxId);
    jobDataMap.put(REMOTE_RESOURCE_CRN, crn);

    return JobBuilder.newJob(clazz)
            .withIdentity(sdxId, JOB_GROUP)
            .withDescription("Checking datalake status Job")
            .usingJobData(jobDataMap)
            .storeDurably()
            .build();
}
 
Example #15
Source File: ExternalDataJoiner.java    From Eagle with Apache License 2.0 5 votes vote down vote up
public ExternalDataJoiner(Class<? extends Job> jobCls, Config config) throws Exception{
	Map<String, Object> map = new HashMap<String, Object>();
       for(Map.Entry<String, ConfigValue> entry : config.getObject("eagleProps").entrySet()){
           map.put(entry.getKey(), entry.getValue().unwrapped());
       }

	init(jobCls, map);
}
 
Example #16
Source File: AutowiringJobFactory.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Job newJob (TriggerFiredBundle bundle, Scheduler scheduler)
   throws SchedulerException
{
   Job job = super.newJob (bundle, scheduler);
   beanFactory.autowireBean (job);
   return job;
}
 
Example #17
Source File: GlassJobFactory.java    From quartz-glass with Apache License 2.0 5 votes vote down vote up
private void populateTriggerDataMapTargetObject(TriggerFiredBundle bundle, Job job) {
    PojoJobMeta pojoJobMeta = getPojoJobMeta(bundle.getJobDetail());

    Object targetObject = pojoJobMeta == null ? job : pojoJobMeta.getTargetObject();
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());
    buildAccessor(targetObject).setPropertyValues(pvs, true);
}
 
Example #18
Source File: AdaptableJobFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Adapt the given job object to the Quartz Job interface.
 * <p>The default implementation supports straight Quartz Jobs
 * as well as Runnables, which get wrapped in a DelegatingJob.
 * @param jobObject the original instance of the specified job class
 * @return the adapted Quartz Job instance
 * @throws Exception if the given job could not be adapted
 * @see DelegatingJob
 */
protected Job adaptJob(Object jobObject) throws Exception {
	if (jobObject instanceof Job) {
		return (Job) jobObject;
	}
	else if (jobObject instanceof Runnable) {
		return new DelegatingJob((Runnable) jobObject);
	}
	else {
		throw new IllegalArgumentException(
				"Unable to execute job class [" + jobObject.getClass().getName() +
				"]: only [org.quartz.Job] and [java.lang.Runnable] supported.");
	}
}
 
Example #19
Source File: JobConfig.java    From javabase with Apache License 2.0 5 votes vote down vote up
public JobConfig(String clientId, String jobName, String groupName, String triggerKey, String jobDetail,
		String jobCron, Class<? extends Job> jobClass) {
	this.clientId = clientId;
	this.jobName = jobName;
	this.groupName = groupName;
	this.triggerKey = triggerKey;
	this.jobDetail = jobDetail;
	this.jobCron = jobCron;
	this.jobClass=jobClass;
	this.ip=new LocalHostService().getIp();
}
 
Example #20
Source File: AdaptableJobFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Adapt the given job object to the Quartz Job interface.
 * <p>The default implementation supports straight Quartz Jobs
 * as well as Runnables, which get wrapped in a DelegatingJob.
 * @param jobObject the original instance of the specified job class
 * @return the adapted Quartz Job instance
 * @throws Exception if the given job could not be adapted
 * @see DelegatingJob
 */
protected Job adaptJob(Object jobObject) throws Exception {
	if (jobObject instanceof Job) {
		return (Job) jobObject;
	}
	else if (jobObject instanceof Runnable) {
		return new DelegatingJob((Runnable) jobObject);
	}
	else {
		throw new IllegalArgumentException("Unable to execute job class [" + jobObject.getClass().getName() +
				"]: only [org.quartz.Job] and [java.lang.Runnable] supported.");
	}
}
 
Example #21
Source File: Context.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public <T extends Job> void scheduleLocal(Class<T> cls, Trigger existTrigger) throws Exception {
	JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(cls.getName(), clazz.getName())
			.withDescription(Config.node()).build();
	Trigger trigger = TriggerBuilder.newTrigger().withIdentity(cls.getName(), clazz.getName())
			.withDescription("scheduleLocal").withSchedule(existTrigger.getScheduleBuilder()).build();
	scheduler.scheduleJob(jobDetail, trigger);
}
 
Example #22
Source File: GuiceJobFactory.java    From Raigad with Apache License 2.0 5 votes vote down vote up
@Override
public Job newJob(TriggerFiredBundle bundle) throws SchedulerException
{
    JobDetail jobDetail = bundle.getJobDetail();
    Class<?> jobClass = jobDetail.getJobClass();
    Job job = (Job) guice.getInstance(jobClass);
    guice.injectMembers(job);
    return job;
}
 
Example #23
Source File: DynamicJobFactory.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException {
    Map<String, Object> data = bundle.getJobDetail().getJobDataMap();
    String jobId = (String) data.get(JOB_ID_KEY);
    if (null == jobId || bundle.getJobDetail().getJobClass() != DynamicJob.class) {
        return defaultFactory.newJob(bundle, scheduler);
    }
    return  context -> scheduleJobExecutor.doExecuteJob(jobId, data);
}
 
Example #24
Source File: SchedulerService.java    From opencron with Apache License 2.0 5 votes vote down vote up
public void initQuartz(Job jobExecutor) throws SchedulerException {
    //quartz job
    logger.info("[opencron] init quartzJob...");
    List<JobVo> jobs = jobService.getJobVo(Opencron.ExecType.AUTO, Opencron.CronType.QUARTZ);
    for (JobVo job : jobs) {
        try {
            put(job,jobExecutor);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    startQuartz();
}
 
Example #25
Source File: CronSetup.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public void registerCronJob(final String givenName, final Class< ? extends Job> jobClass, final String cronExpression,
    final Object... params)
{
  if (jobClass != null) {
    String name = givenName;
    if (StringUtils.isBlank(name) == true) {
      name = "generatedExternalName " + jobClass.getName() + " " + System.currentTimeMillis();
    }
    // default is run every 10 minutes
    createCron(name, jobClass, "0 */10 * * * ?", cronExpression, params);
  }
}
 
Example #26
Source File: SchedulerService.java    From opencron with Apache License 2.0 5 votes vote down vote up
public void put(JobVo job, Job jobBean) throws SchedulerException {
    TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobId().toString());
    CronTrigger cronTrigger = newTrigger().withIdentity(triggerKey).withSchedule(cronSchedule(job.getCronExp())).build();

    //when exists then delete..
    if (exists(job.getJobId())) {
        this.remove(job.getJobId());
    }
    //add new job 。。。
    JobDetail jobDetail = JobBuilder.newJob(jobBean.getClass()).withIdentity(JobKey.jobKey(job.getJobId().toString())).build();
    jobDetail.getJobDataMap().put(job.getJobId().toString(), job);
    jobDetail.getJobDataMap().put("jobBean", jobBean);
    Date date = quartzScheduler.scheduleJob(jobDetail, cronTrigger);
    logger.info("opencron: add success,cronTrigger:{}", cronTrigger, date);
}
 
Example #27
Source File: JobDetailSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param attrMap the attributes that define the job
 * @return JobDetail
 */
public static JobDetail newJobDetail(Map<String, Object> attrMap)
    throws ClassNotFoundException
{
    JobDetailImpl jobDetail = new JobDetailImpl();

    int i = 0;
    jobDetail.setName((String) attrMap.get(ITEM_NAMES[i++]));
    jobDetail.setGroup((String) attrMap.get(ITEM_NAMES[i++]));
    jobDetail.setDescription((String) attrMap.get(ITEM_NAMES[i++]));
    Class<?> jobClass = Class.forName((String) attrMap.get(ITEM_NAMES[i++]));
    @SuppressWarnings("unchecked")
    Class<? extends Job> jobClassTyped = (Class<? extends Job>)jobClass;
    jobDetail.setJobClass(jobClassTyped);
    if(attrMap.containsKey(ITEM_NAMES[i])) {
        @SuppressWarnings("unchecked")
        Map<String, Object> map = (Map<String, Object>)attrMap.get(ITEM_NAMES[i]); 
        jobDetail.setJobDataMap(JobDataMapSupport.newJobDataMap(map));
    }
    i++;
    if(attrMap.containsKey(ITEM_NAMES[i])) {
        jobDetail.setDurability((Boolean) attrMap.get(ITEM_NAMES[i]));
    }
    i++;
    if(attrMap.containsKey(ITEM_NAMES[i])) {
        jobDetail.setRequestsRecovery((Boolean) attrMap.get(ITEM_NAMES[i]));
    }
    i++;
    
    return jobDetail;
}
 
Example #28
Source File: AuroraCronJobFactory.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException {
  checkState(AuroraCronJob.class.equals(bundle.getJobDetail().getJobClass()),
      "Quartz tried to run a type of job we don't know about: %s",
      bundle.getJobDetail().getJobClass());

  return auroraCronJobProvider.get();
}
 
Example #29
Source File: ExecuteBIDocumentJob.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
	logger.debug("IN");

	Job job = new XExecuteBIDocumentJob();
	job.execute(jobExecutionContext);
	logger.debug("OUT");
}
 
Example #30
Source File: SchedulerUtilsTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateJobDetail() {
    //given
    String identity = "foo";
    String groupName = "bar";
    Class<? extends Job> clazz = InfoJob.class;
    
    //when
    JobDetail jobDetail = SchedulerUtils.createJobDetail(identity, groupName, clazz);
    
    //then
    assertThat(jobDetail, not(nullValue()));
}