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

The following examples show how to use org.quartz.Scheduler#addJob() . 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: GetArchivesJob.java    From sakai with Educational Community License v2.0 7 votes vote down vote up
private void scheduleImport(String file, String siteId) {
    JobDataMap jobData = new JobDataMap();
    jobData.put("zip", file);
    if (siteId != null) {
        jobData.put("siteId", siteId);
    }

    JobDetail jobDetail = JobBuilder.newJob(ImportJob.class)
            .withIdentity("Import Job")
            .setJobData(jobData)
            .build();
    Scheduler scheduler = schedulerManager.getScheduler();
    try {
        scheduler.addJob(jobDetail, true, true);
        scheduler.triggerJob(jobDetail.getKey());
    } catch (SchedulerException e) {
        log.warn("Problem adding job to scheduler to import "+ file, e);
    }
}
 
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: GetArchivesJob.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private void scheduleImport(String file, String siteId) {
    JobDataMap jobData = new JobDataMap();
    jobData.put("zip", file);
    if (siteId != null) {
        jobData.put("siteId", siteId);
    }

    JobDetail jobDetail = JobBuilder.newJob(ImportJob.class)
            .withIdentity("Import Job")
            .setJobData(jobData)
            .build();
    Scheduler scheduler = schedulerManager.getScheduler();
    try {
        scheduler.addJob(jobDetail, true, true);
        scheduler.triggerJob(jobDetail.getKey());
    } catch (SchedulerException e) {
        log.warn("Problem adding job to scheduler to import "+ file, e);
    }
}
 
Example 5
Source File: SchedulerTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testShutdownWithoutWaitIsUnclean() throws Exception {
  CyclicBarrier barrier = new CyclicBarrier(2);
  Scheduler scheduler = createScheduler("testShutdownWithoutWaitIsUnclean", 8);
  try {
    scheduler.getContext().put(BARRIER, barrier);
    scheduler.start();
    scheduler.addJob(newJob().ofType(UncleanShutdownJob.class).withIdentity("job").storeDurably().build(), false);
    scheduler.scheduleJob(newTrigger().forJob("job").startNow().build());
    while (scheduler.getCurrentlyExecutingJobs().isEmpty()) {
      Thread.sleep(50);
    }
  }
  finally {
    scheduler.shutdown(false);
  }

  barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);

  Thread jobThread = (Thread) scheduler.getContext().get(JOB_THREAD);
  assertThat(jobThread, notNullValue());
  jobThread.join(TimeUnit.SECONDS.toMillis(TEST_TIMEOUT_SECONDS));
}
 
Example 6
Source File: KCBInitializer.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    GlobalKCBServiceLocator.init(beanFactory);
    // kill the reference, our job is done
    beanFactory = null;

    Scheduler scheduler = getScheduler()==null?KSBServiceLocator.getScheduler():getScheduler();
    scheduler.addJob(messageProcessingJobDetail, true);

    addTriggerToScheduler(messageProcessingTrigger);
}
 
Example 7
Source File: AutoRun.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void init() {
    if (config == null || serverConfigurationService.getBoolean(config, false)) {
        log.info("AutoRun running");
        Scheduler scheduler = schedulerManager.getScheduler();

        for (JobBeanWrapper job : startup) {
            try {
                JobDataMap jobData = new JobDataMap();
                jobData.put(JobBeanWrapper.SPRING_BEAN_NAME, job.getBeanId());
                jobData.put(JobBeanWrapper.JOB_NAME, job.getJobName());

                JobDetail jobDetail = JobBuilder.newJob(job.getJobClass())
                        .withIdentity(job.getJobName(), null)
                        .setJobData(jobData)
                        .build();

                // Non durable job that will get removed
                scheduler.addJob(jobDetail, true, true);
                scheduler.triggerJob(jobDetail.getKey());
                log.info("Triggered job: {}", job.getJobName());
            } catch (SchedulerException se) {
                log.warn("Failed to run job: {}", startup, se);
            }

        }
    }
}
 
Example 8
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 9
Source File: AutoRun.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void init() {
    if (config == null || serverConfigurationService.getBoolean(config, false)) {
        log.info("AutoRun running");
        Scheduler scheduler = schedulerManager.getScheduler();

        for (JobBeanWrapper job : startup) {
            try {
                JobDataMap jobData = new JobDataMap();
                jobData.put(JobBeanWrapper.SPRING_BEAN_NAME, job.getBeanId());
                jobData.put(JobBeanWrapper.JOB_NAME, job.getJobName());

                JobDetail jobDetail = JobBuilder.newJob(job.getJobClass())
                        .withIdentity(job.getJobName(), null)
                        .setJobData(jobData)
                        .build();

                // Non durable job that will get removed
                scheduler.addJob(jobDetail, true, true);
                scheduler.triggerJob(jobDetail.getKey());
                log.info("Triggered job: {}", job.getJobName());
            } catch (SchedulerException se) {
                log.warn("Failed to run job: {}", startup, se);
            }

        }
    }
}
 
Example 10
Source File: SchedulerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testShutdownWithWaitIsClean() throws Exception {
  final AtomicBoolean shutdown = new AtomicBoolean(false);
  List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>());
  CyclicBarrier barrier = new CyclicBarrier(2);
  final Scheduler scheduler = createScheduler("testShutdownWithWaitIsClean", 8);
  try {
    scheduler.getContext().put(BARRIER, barrier);
    scheduler.getContext().put(DATE_STAMPS, jobExecTimestamps);
    scheduler.start();
    scheduler.addJob(newJob().ofType(TestJobWithSync.class).withIdentity("job").storeDurably().build(), false);
    scheduler.scheduleJob(newTrigger().forJob("job").startNow().build());
    while (scheduler.getCurrentlyExecutingJobs().isEmpty()) {
      Thread.sleep(50);
    }
  }
  finally {
    Thread t = new Thread()
    {
      @Override
      public void run() {
        try {
          scheduler.shutdown(true);
          shutdown.set(true);
        }
        catch (SchedulerException ex) {
          throw new RuntimeException(ex);
        }
      }
    };
    t.start();
    Thread.sleep(1000);
    assertFalse(shutdown.get());
    barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    t.join();
  }
}
 
Example 11
Source File: SchedulerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testDurableStorageFunctions() throws Exception {
  Scheduler sched = createScheduler("testDurableStorageFunctions", 2);
  try {
    // test basic storage functions of scheduler...

    JobDetail job = newJob()
        .ofType(TestJob.class)
        .withIdentity("j1")
        .storeDurably()
        .build();

    assertFalse("Unexpected existence of job named 'j1'.", sched.checkExists(jobKey("j1")));

    sched.addJob(job, false);

    assertTrue("Unexpected non-existence of job named 'j1'.", sched.checkExists(jobKey("j1")));

    JobDetail nonDurableJob = newJob()
        .ofType(TestJob.class)
        .withIdentity("j2")
        .build();

    try {
      sched.addJob(nonDurableJob, false);
      fail("Storage of non-durable job should not have succeeded.");
    }
    catch (SchedulerException expected) {
      assertFalse("Unexpected existence of job named 'j2'.", sched.checkExists(jobKey("j2")));
    }

    sched.addJob(nonDurableJob, false, true);

    assertTrue("Unexpected non-existence of job named 'j2'.", sched.checkExists(jobKey("j2")));
  }
  finally {
    sched.shutdown(true);
  }
}
 
Example 12
Source File: ExportResource.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@POST
@Path("/cockpitData")
@Produces(MediaType.APPLICATION_JSON)
public Response exportCockpitDocumentWidgetData(DocumentExportConf documentExportConf) {
	logger.debug("IN");

	logger.debug(String.format("document id: %s", documentExportConf.getDocumentId()));
	logger.debug(String.format("document label: %s", documentExportConf.getDocumentLabel()));
	logger.debug(String.format("export type: %s", documentExportConf.getExportType()));
	logger.debug(String.format("parameters: %s", documentExportConf.getParameters()));

	JobDetail exportJob = new CockpitDataExportJobBuilder().setDocumentExportConf(documentExportConf).setLocale(request.getLocale())
			.setUserProfile(UserProfileManager.getProfile()).build();
	logger.debug("Created export job");

	try {
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
		scheduler.addJob(exportJob, true);
		scheduler.triggerJob(exportJob.getName(), exportJob.getGroup());
		logger.debug("Export job triggered ");
	} catch (SchedulerException e) {
		String msg = String.format("Error during scheduling of export job for cokcpit document %d", documentExportConf.getDocumentLabel());
		logger.error(msg, e);
		throw new SpagoBIRuntimeException(msg);
	}
	logger.debug("OUT");
	return Response.ok().entity(exportJob.getName()).build();

}
 
Example 13
Source File: ExportResource.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Schedula a job to clean old export.
 *
 * @throws SchedulerException In case of error during scheduling
 */
private void scheduleCleanUp() throws SchedulerException {

	UserProfile userProfile = UserProfileManager.getProfile();
	String resoursePath = SpagoBIUtilities.getResourcePath();

	String jobName = String.format("delete-old-export-for-%s", userProfile.getUserId());
	String jobGroup = "delete-old-export";
	String jobDescription = String.format("Delete old exports for user %s", userProfile.getUserId());

	JobDataMap jobDataMap = new JobDataMap();

	jobDataMap.put(ExportDeleteOldJob.MAP_KEY_RESOURCE_PATH, resoursePath);
	jobDataMap.put(ExportDeleteOldJob.MAP_KEY_USER_PROFILE, userProfile);

	JobDetail job = new JobDetail(jobName, jobGroup, ExportDeleteOldJob.class);

	job.setDescription(jobDescription);
	job.setJobDataMap(jobDataMap);

	Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

	scheduler.addJob(job, true);
	scheduler.triggerJob(job.getName(), job.getGroup());

}
 
Example 14
Source File: SchedulerTool.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public String processCreateJob()
{
  Scheduler scheduler = schedulerManager.getScheduler();
  if (scheduler == null)
  {
    log.error("Scheduler is down!");
    return "error";
  }
  try
  {
      //get a JobDetail object in case one is already in the Session
      //  (eg. if we have returned her from a validation error
     JobDetail jd = getJobDetail();
     JobBeanWrapper job = getSchedulerManager().getJobBeanWrapper(selectedClass);

    jobName = escapeEntities(jobName);

     if (job != null)
     {
         // create a new JobDetail object for this job
         jd = createJobDetail(job);

  	   //we have a job, so check to see if properties need to be set    	   
         if (ConfigurableJobBeanWrapper.class.isAssignableFrom(job.getClass()))
         {
      	   //this job is configurable, provide a screen to edit properties
             final ConfigurableJobBeanWrapper
                 configurableJob = (ConfigurableJobBeanWrapper)job;

             // prepare properties for use within the property configuration UI
             setConfigurableJobBeanWrapper (configurableJob);
             setJobDetail(jd);

             return "edit_properties";
         }
         else
         {
      	   //not a configurable job, create the job and move on
             setConfigurableJobBeanWrapper(null);
         }
     }
     else
     {
  	   // this is not a job configured via a JobBeanWrapper
  	   // assume the class is a Job and schedule its execution
        setConfigurableJobBeanWrapper(null);
        jd = JobBuilder.newJob((Class<? extends Job>) Class.forName(selectedClass.toString()))
                .withIdentity(jobName, Scheduler.DEFAULT_GROUP)
                .requestRecovery()
                .storeDurably()
                .build();
     }
     
     // create the job and show the list of jobs
    scheduler.addJob(jd, false);
    jobName = null;
    // Clear out the form.
    selectedClass = null;
    processRefreshJobs();
    return "jobs";
  }
  catch (Exception e)
  {
    log.error("Failed to create job.", e);
    return "error";
  }
}
 
Example 15
Source File: QuartzUtils.java    From quartz-web with Apache License 2.0 4 votes vote down vote up
public static void addJob(JobDetail jobDetail,
                          boolean replace, boolean storeNonDurableWhileAwaitingScheduling, Scheduler scheduler) throws SchedulerException {

    scheduler.addJob(jobDetail, replace, storeNonDurableWhileAwaitingScheduling);
}
 
Example 16
Source File: QuartzUtils.java    From quartz-web with Apache License 2.0 4 votes vote down vote up
public static void addJob(JobDetail jobDetail,
                          boolean replace,Scheduler scheduler) throws SchedulerException {
    scheduler.addJob(jobDetail, replace);
}
 
Example 17
Source File: SchedulerTool.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public String processCreateJob()
{
  Scheduler scheduler = schedulerManager.getScheduler();
  if (scheduler == null)
  {
    log.error("Scheduler is down!");
    return "error";
  }
  try
  {
      //get a JobDetail object in case one is already in the Session
      //  (eg. if we have returned her from a validation error
     JobDetail jd = getJobDetail();
     JobBeanWrapper job = getSchedulerManager().getJobBeanWrapper(selectedClass);

    jobName = escapeEntities(jobName);

     if (job != null)
     {
         // create a new JobDetail object for this job
         jd = createJobDetail(job);

  	   //we have a job, so check to see if properties need to be set    	   
         if (ConfigurableJobBeanWrapper.class.isAssignableFrom(job.getClass()))
         {
      	   //this job is configurable, provide a screen to edit properties
             final ConfigurableJobBeanWrapper
                 configurableJob = (ConfigurableJobBeanWrapper)job;

             // prepare properties for use within the property configuration UI
             setConfigurableJobBeanWrapper (configurableJob);
             setJobDetail(jd);

             return "edit_properties";
         }
         else
         {
      	   //not a configurable job, create the job and move on
             setConfigurableJobBeanWrapper(null);
         }
     }
     else
     {
  	   // this is not a job configured via a JobBeanWrapper
  	   // assume the class is a Job and schedule its execution
        setConfigurableJobBeanWrapper(null);
        jd = JobBuilder.newJob((Class<? extends Job>) Class.forName(selectedClass.toString()))
                .withIdentity(jobName, Scheduler.DEFAULT_GROUP)
                .requestRecovery()
                .storeDurably()
                .build();
     }
     
     // create the job and show the list of jobs
    scheduler.addJob(jd, false);
    jobName = null;
    // Clear out the form.
    selectedClass = null;
    processRefreshJobs();
    return "jobs";
  }
  catch (Exception e)
  {
    log.error("Failed to create job.", e);
    return "error";
  }
}
 
Example 18
Source File: SchedulerTest.java    From nexus-public with Eclipse Public License 1.0 3 votes vote down vote up
@Test
public void testAbilityToFireImmediatelyWhenStartedBeforeWithTriggerJob() throws Exception {
  List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>());
  CyclicBarrier barrier = new CyclicBarrier(2);

  Scheduler sched = createScheduler("testAbilityToFireImmediatelyWhenStartedBeforeWithTriggerJob", 5);
  sched.getContext().put(BARRIER, barrier);
  sched.getContext().put(DATE_STAMPS, jobExecTimestamps);

  sched.start();

  Thread.yield();

  JobDetail job1 = JobBuilder.newJob(TestJobWithSync.class).withIdentity("job1").storeDurably().build();
  sched.addJob(job1, false);

  long sTime = System.currentTimeMillis();

  sched.triggerJob(job1.getKey());

  barrier.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);

  sched.shutdown(true);

  long fTime = jobExecTimestamps.get(0);

  assertTrue("Immediate trigger did not fire within a reasonable amount of time.",
      (fTime - sTime < 7000L));  // This is dangerously subjective!  but what else to do?
}
 
Example 19
Source File: QuartzManager.java    From quartz-web with Apache License 2.0 3 votes vote down vote up
/**
 * 添加job
 *
 * @param schedulerName
 * @param jobDetail
 * @return
 * @throws SchedulerException
 */
public void addJob(String schedulerName, JobDetail jobDetail, boolean replace) throws SchedulerException {
    Assert.notEmpty(schedulerName, "schedulerName can not be empty");
    Assert.notNull(jobDetail, "jobDetail can not be null");
    Scheduler scheduler = this.getAssertScheduler(schedulerName);
    scheduler.addJob(jobDetail, replace);
}