org.quartz.JobDetail Java Examples

The following examples show how to use org.quartz.JobDetail. 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: 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 #2
Source File: ReminderJob.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
public static JobDetail createDetails(MessageChannel channel, Member member, String message) {
    String userId;
    String guildId = null;
    if (channel instanceof PrivateChannel) {
        userId = ((PrivateChannel) channel).getUser().getId();
    } else {
        guildId = member.getGuild().getId();
        userId = member.getUser().getId();
    }
    return JobBuilder
            .newJob(ReminderJob.class)
            .withIdentity(GROUP + " - " + UUID.randomUUID(), GROUP)
            .usingJobData(ATTR_GUILD_ID, guildId)
            .usingJobData(ATTR_USER_ID, userId)
            .usingJobData(ATTR_CHANNEL_ID, channel.getId())
            .usingJobData(ATTR_MESSAGE, message)
            .build();
}
 
Example #3
Source File: RedisJobStoreTest.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
@Test
public void clearAllSchedulingData() throws Exception {
    // create and store some jobs, triggers, and calendars
    Map<JobDetail, Set<? extends Trigger>> jobsAndTriggers = getJobsAndTriggers(2, 2, 2, 2);
    jobStore.storeJobsAndTriggers(jobsAndTriggers, false);

    // ensure that the jobs, triggers, and calendars were stored
    assertEquals(2, (long) jedis.scard(schema.jobGroupsSet()));
    assertEquals(4, (long) jedis.scard(schema.jobsSet()));
    assertEquals(8, (long) jedis.scard(schema.triggerGroupsSet()));
    assertEquals(16, (long) jedis.scard(schema.triggersSet()));

    jobStore.clearAllSchedulingData();

    assertEquals(0, (long) jedis.scard(schema.jobGroupsSet()));
    assertEquals(0, (long) jedis.scard(schema.jobsSet()));
    assertEquals(0, (long) jedis.scard(schema.triggerGroupsSet()));
    assertEquals(0, (long) jedis.scard(schema.triggersSet()));
}
 
Example #4
Source File: CmsTaskAct.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 开始任务调度
 * @param task 任务
 * @param taskCode 任务名称
 * @throws ParseException
 * @throws SchedulerException
 * @throws ClassNotFoundException
 */
private void startTask(CmsTask task,String taskCode) throws ParseException, SchedulerException, ClassNotFoundException{
	String cronExpress=manager.getCronExpressionFromDB(task.getId());
	System.out.println(cronExpress);
	if(cronExpress.indexOf("null")==-1){
		JobDetail jobDetail = new JobDetail();
		jobDetail.setName(taskCode);
		jobDetail.setGroup(Scheduler.DEFAULT_GROUP);
		jobDetail.setJobClass(getClassByTask(task.getJobClass()));
		//任务需要参数attr属性 
		jobDetail.setJobDataMap(getJobDataMap(task.getAttr()));
		CronTrigger cronTrigger = new CronTrigger("cron_" + taskCode,Scheduler.DEFAULT_GROUP, jobDetail.getName(),Scheduler.DEFAULT_GROUP);
		cronTrigger.setCronExpression(cronExpress);
		scheduler.scheduleJob(jobDetail, cronTrigger); 
	}
}
 
Example #5
Source File: JobSchedulerTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void scheduleInactive() throws SchedulerException {
  ScheduledJob scheduledJob = scheduledJobFactory.create();
  scheduledJob.setId(id);
  scheduledJob.set(ScheduledJobMetadata.CRON_EXPRESSION, "	0/20 * * * * ?");
  scheduledJob.set(ScheduledJobMetadata.NAME, "name");
  scheduledJob.set(ScheduledJobMetadata.ACTIVE, false);
  scheduledJob.setType(scheduledJobType);

  when(quartzScheduler.checkExists(jobKey)).thenReturn(false);

  jobScheduler.schedule(scheduledJob);

  verify(quartzScheduler, Mockito.never())
      .scheduleJob(ArgumentMatchers.any(JobDetail.class), ArgumentMatchers.any(Trigger.class));
}
 
Example #6
Source File: QuartzManager.java    From quartz-web with Apache License 2.0 6 votes vote down vote up
public JobDetail addStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String jobClass,
                                    Object[] constructorArguments, String jobClassMethodName,
                                    Object[] jobClassMethodArgs, String description) throws SchedulerException {
    Assert.notNull(jobClass, "jobClass can not be null");
    Assert.notEmpty(schedulerName, "schedulerName can not be empty");
    Assert.notEmpty(jobName, "jobName can not be empty");
    Assert.notEmpty(jobGroup, "jobGroup can not be empty");
    Assert.notEmpty(jobClassMethodName, "jobClassMethodName can not be empty");
    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put("jobClass", jobClass);
    jobDataMap.put("constructorArguments", constructorArguments);
    jobDataMap.put("jobClassMethodName", jobClassMethodName);
    jobDataMap.put("jobClassMethodArgs", jobClassMethodArgs);
    JobDetail jobDetail = JobBuilder.newJob(StatefulMethodInvokeJob.class).withIdentity(jobName, jobGroup)
            .withDescription(description).setJobData(jobDataMap).storeDurably().build();
    addJob(schedulerName, jobDetail);
    return jobDetail;
}
 
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: JobStoreImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void storeJob(final ODatabaseDocumentTx db, final JobDetail jobDetail, final boolean replaceExisting)
    throws JobPersistenceException
{
  log.debug("Store job: jobDetail={}, replaceExisting={}", jobDetail, replaceExisting);

  JobDetailEntity entity = jobDetailEntityAdapter.readByKey(db, jobDetail.getKey());
  if (entity == null) {
    // no existing entity, add new one
    entity = new JobDetailEntity(jobDetail);
    jobDetailEntityAdapter.addEntity(db, entity);
  }
  else {
    // otherwise entity exists, maybe replace if allowed
    if (replaceExisting) {
      entity.setValue(jobDetail);
      jobDetailEntityAdapter.editEntity(db, entity);
    }
    else {
      throw new ObjectAlreadyExistsException(jobDetail);
    }
  }
}
 
Example #9
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 #10
Source File: SchedulerTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testAbilityToFireImmediatelyWhenStartedAfter() throws Exception {
  List<Long> jobExecTimestamps = Collections.synchronizedList(new ArrayList<Long>());
  CyclicBarrier barrier = new CyclicBarrier(2);

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

  JobDetail job1 = JobBuilder.newJob(TestJobWithSync.class).withIdentity("job1").build();
  Trigger trigger1 = TriggerBuilder.newTrigger().forJob(job1).build();

  long sTime = System.currentTimeMillis();

  sched.scheduleJob(job1, trigger1);
  sched.start();

  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 #11
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 #12
Source File: JobTransactionNameInstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
void verifyJobDetails(JobDetail job) {
    await().untilAsserted(() -> assertThat(reporter.getTransactions().size()).isEqualTo(1));
    assertThat(reporter.getTransactions().get(0).getType()).isEqualToIgnoringCase("scheduled");
    assertThat(reporter.getTransactions().get(0).getNameAsString())
        .isEqualToIgnoringCase(String.format("%s.%s", job.getKey().getGroup(), job.getKey().getName()));
    assertThat(reporter.getTransactions().get(0).getFrameworkName()).isEqualTo("Quartz");
    assertThat(reporter.getTransactions().get(0).getFrameworkVersion()).isEqualTo("2.3.1");
}
 
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: 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 scheduleJob(JobDetail jobDetail, Trigger trigger)
    throws SchedulerException {
    try {
        return getRemoteScheduler().scheduleJob(schedCtxt, jobDetail,
                trigger);
    } catch (RemoteException re) {
        throw invalidateHandleCreateException(
                "Error communicating with remote scheduler.", re);
    }
}
 
Example #15
Source File: QuartzSchedulerMBeanImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public TabularData getAllJobDetails() throws Exception {
    try {
        List<JobDetail> detailList = new ArrayList<JobDetail>();
        for (String jobGroupName : scheduler.getJobGroupNames()) {
            for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(jobGroupName))) {
                detailList.add(scheduler.getJobDetail(jobKey));
            }
        }
        return JobDetailSupport.toTabularData(detailList.toArray(new JobDetail[detailList.size()]));
    } catch (Exception e) {
        throw newPlainException(e);
    }
}
 
Example #16
Source File: SpringBootAsyncProducerApplication.java    From Spring-Boot-2.0-Projects with MIT License 5 votes vote down vote up
@Bean
public CronTriggerFactoryBean trigger(JobDetail job, @Value("${images.cron}") String imagesCron) {
    CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
    cronTriggerFactoryBean.setCronExpression(imagesCron);
    cronTriggerFactoryBean.setJobDetail(job);
    return cronTriggerFactoryBean;
}
 
Example #17
Source File: StdJDBCDelegate.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Insert the job detail record.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param job
 *          the job to insert
 * @return number of rows inserted
 * @throws IOException
 *           if there were problems serializing the JobDataMap
 */
public int insertJobDetail(Connection conn, JobDetail job)
    throws IOException, SQLException {
    ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap());

    PreparedStatement ps = null;

    int insertResult = 0;

    try {
        ps = conn.prepareStatement(rtp(INSERT_JOB_DETAIL));
        ps.setString(1, job.getName());
        ps.setString(2, job.getGroup());
        ps.setString(3, job.getDescription());
        ps.setString(4, job.getJobClass().getName());
        setBoolean(ps, 5, job.isDurable());
        setBoolean(ps, 6, job.isVolatile());
        setBoolean(ps, 7, job.isStateful());
        setBoolean(ps, 8, job.requestsRecovery());
        setBytes(ps, 9, baos);

        insertResult = ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }

    if (insertResult > 0) {
        String[] jobListeners = job.getJobListenerNames();
        for (int i = 0; jobListeners != null && i < jobListeners.length; i++) {
            insertJobListener(conn, job, jobListeners[i]);
        }
    }

    return insertResult;
}
 
Example #18
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 #19
Source File: QuartzManager.java    From quartz-web with Apache License 2.0 5 votes vote down vote up
/**
 * 获取全部trigger
 * @return
 * @throws SchedulerException
 */
public List<? extends Trigger> getAllTriggers() throws SchedulerException {
    List<Trigger> triggers = new ArrayList<Trigger>();
    List<Scheduler> schedulers = this.getSchedulers();
    for (Scheduler scheduler : schedulers) {
        List<JobDetail> jobDetails = getAllJobsOfScheduler(scheduler.getSchedulerName());
        List<Trigger> triggersOfScheduler = new ArrayList<Trigger>();
        for (JobDetail jobDetail : jobDetails) {
            List<? extends Trigger> triggersOfJob = QuartzUtils.getTriggersOfJob(jobDetail, scheduler);
            triggersOfScheduler.addAll(triggersOfJob);
        }
        triggers.addAll(triggersOfScheduler);
    }
    return triggers;
}
 
Example #20
Source File: SchedulerServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String getStatus(JobDetail jobDetail) {
    if ( jobDetail == null ) {
        return FAILED_JOB_STATUS_CODE;
    }
    KfsModuleServiceImpl moduleService = (KfsModuleServiceImpl)
        SpringContext.getBean(KualiModuleService.class).getResponsibleModuleServiceForJob(jobDetail.getName());
    //If the module service has status information for a job, get the status from it
    //else get status from job detail data map
    return (moduleService!=null && moduleService.isExternalJob(jobDetail.getName()))
                ? moduleService.getExternalJobStatus(jobDetail.getName())
                : jobDetail.getJobDataMap().getString(SchedulerServiceImpl.JOB_STATUS_PARAMETER);
}
 
Example #21
Source File: SchedulerHelperTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Test
public void testScheduleCronJob() throws SchedulerException, ParseException {
	JobDetail jobDetail = createServiceJob("testJob"+Math.random());

	schedulerHelper.scheduleJob(jobDetail, "0 0 1 * * ?");
	assertTrue(schedulerHelper.contains(jobDetail.getKey().getName()));
}
 
Example #22
Source File: SchedulerManager.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
public static void scheduleChannelReg(String identifier) {
  // add another job for registering channel to ekstep.
  // 1- create a job and bind with class which is implementing Job
  // interface.
  JobDetail channelRegistrationJob =
      JobBuilder.newJob(ChannelRegistrationScheduler.class)
          .requestRecovery(true)
          .withDescription("Scheduler for channel registration")
          .withIdentity("channelRegistrationScheduler", identifier)
          .build();

  // 2- Create a trigger object that will define frequency of run.
  // It will run only once after server startup
  Trigger channelRegistrationTrigger =
      TriggerBuilder.newTrigger()
          .withIdentity("channelRegistrationScheduler", identifier)
          .withSchedule(SimpleScheduleBuilder.repeatMinutelyForTotalCount(1))
          .build();
  try {
    if (scheduler.checkExists(channelRegistrationJob.getKey())) {
      scheduler.deleteJob(channelRegistrationJob.getKey());
    }
    scheduler.scheduleJob(channelRegistrationJob, channelRegistrationTrigger);
    scheduler.start();
    ProjectLogger.log(
        "SchedulerManager:scheduleChannelReg: channelRegistration schedular started",
        LoggerEnum.INFO.name());
  } catch (Exception e) {
    ProjectLogger.log(e.getMessage(), e);
  }
}
 
Example #23
Source File: JobStoreSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>
 * Inform the <code>JobStore</code> that the scheduler has completed the
 * firing of the given <code>Trigger</code> (and the execution its
 * associated <code>Job</code>), and that the <code>{@link org.quartz.JobDataMap}</code>
 * in the given <code>JobDetail</code> should be updated if the <code>Job</code>
 * is stateful.
 * </p>
 */
public void triggeredJobComplete(final OperableTrigger trigger,
        final JobDetail jobDetail, final CompletedExecutionInstruction triggerInstCode) {
    retryExecuteInNonManagedTXLock(
        LOCK_TRIGGER_ACCESS,
        new VoidTransactionCallback() {
            public void executeVoid(Connection conn) throws JobPersistenceException {
                triggeredJobComplete(conn, trigger, jobDetail,triggerInstCode);
            }
        });    
}
 
Example #24
Source File: SparkSubmitJob.java    From griffin with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(JobExecutionContext context) {
    JobDetail jd = context.getJobDetail();
    try {
        if (isNeedLivyQueue) {
            //livy batch limit
            livyTaskSubmitHelper.addTaskToWaitingQueue(jd);
        } else {
            saveJobInstance(jd);
        }
    } catch (Exception e) {
        LOGGER.error("Post spark task ERROR.", e);
    }
}
 
Example #25
Source File: StoreCalendarTest.java    From quartz-redis-jobstore with Apache License 2.0 5 votes vote down vote up
@Test(expected = JobPersistenceException.class)
public void removeCalendarWithTrigger() throws Exception {
    // store trigger and job
    JobDetail job = getJobDetail();
    jobStore.storeJob(job, false);
    CronTriggerImpl trigger1 = getCronTrigger("trigger1", "group1", job.getKey());
    jobStore.storeTrigger(trigger1, false);

    jobStore.removeCalendar(trigger1.getCalendarName());
}
 
Example #26
Source File: CronSchedulerJobManger.java    From springbootexamples with Apache License 2.0 5 votes vote down vote up
private void scheduleJob2(Scheduler scheduler) throws SchedulerException{
    JobDetail jobDetail = JobBuilder.newJob(CronJob2.class) .withIdentity("job2", "group2")
    		.usingJobData("serviceCode","Live lesson reminder2").build();
    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?");
    CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger2", "group2") .withSchedule(scheduleBuilder).build();
    scheduler.scheduleJob(jobDetail,cronTrigger);  
}
 
Example #27
Source File: RemoteMBeanScheduler.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>,
 * passing the <code>SchedulingContext</code> associated with this
 * instance.
 * </p>
 */
public void addJob(JobDetail jobDetail, boolean replace, boolean storeNonDurableWhileAwaitingScheduling)
        throws SchedulerException {
    invoke(
            "addJob",
            new Object[] { JobDetailSupport.toCompositeData(jobDetail), replace , storeNonDurableWhileAwaitingScheduling},
            new String[] { CompositeData.class.getName(), boolean.class.getName(), boolean.class.getName() });
}
 
Example #28
Source File: FileBasedSessionManager.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private Scheduler createScheduler(String cronExpr) throws SchedulerException {
    // The scheduler can be started and stopped several times in JUnit tests, but Quartz holds
    // every scheduler instances in a singleton SchedulerRepository. So it's possible to pick up
    // the scheduler which is going to be stopped if we use the same instance name for every scheduler,
    // because CentralDogmaExtension stops the server asynchronously using another thread.
    final String myInstanceId = String.valueOf(hashCode());

    final Properties cfg = new Properties();
    cfg.setProperty("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
    cfg.setProperty("org.quartz.scheduler.instanceName",
                    FileBasedSessionManager.class.getSimpleName() + '@' + myInstanceId);
    cfg.setProperty("org.quartz.scheduler.skipUpdateCheck", "true");
    cfg.setProperty("org.quartz.threadPool.threadCount", "1");

    final Scheduler scheduler = new StdSchedulerFactory(cfg).getScheduler();

    final JobDetail job = newJob(ExpiredSessionDeletingJob.class)
            .usingJobData(newJobDataMap(ImmutableMap.of(ROOT_DIR, rootDir)))
            .build();

    final Trigger trigger = newTrigger()
            .withIdentity(myInstanceId, ExpiredSessionDeletingJob.class.getSimpleName())
            .withSchedule(cronSchedule(cronExpr))
            .build();

    scheduler.scheduleJob(job, trigger);
    return scheduler;
}
 
Example #29
Source File: RoboconfSchedulerTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test( expected = IOException.class )
public void testSaveJob_exception() throws Exception {

	this.scheduler.scheduler = Mockito.mock( Scheduler.class );
	Mockito.when( this.scheduler.scheduler.scheduleJob(
			Mockito.any( JobDetail.class ),
			Mockito.any( Trigger.class ))).thenThrow( new SchedulerException( "For test" ));

	this.scheduler.saveJob( null, "job", "cmd", "0 0 0 ? 1 *", "app" );
}
 
Example #30
Source File: StdJDBCDelegate.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Update the job detail record.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param job
 *          the job to update
 * @return number of rows updated
 * @throws IOException
 *           if there were problems serializing the JobDataMap
 */
public int updateJobDetail(Connection conn, JobDetail job)
    throws IOException, SQLException {
    ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap());

    PreparedStatement ps = null;

    int insertResult = 0;

    try {
        ps = conn.prepareStatement(rtp(UPDATE_JOB_DETAIL));
        ps.setString(1, job.getDescription());
        ps.setString(2, job.getJobClass().getName());
        setBoolean(ps, 3, job.isDurable());
        setBoolean(ps, 4, job.isVolatile());
        setBoolean(ps, 5, job.isStateful());
        setBoolean(ps, 6, job.requestsRecovery());
        setBytes(ps, 7, baos);
        ps.setString(8, job.getName());
        ps.setString(9, job.getGroup());

        insertResult = ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }

    if (insertResult > 0) {
        deleteJobListeners(conn, job.getName(), job.getGroup());

        String[] jobListeners = job.getJobListenerNames();
        for (int i = 0; jobListeners != null && i < jobListeners.length; i++) {
            insertJobListener(conn, job, jobListeners[i]);
        }
    }

    return insertResult;
}