org.quartz.SimpleTrigger Java Examples

The following examples show how to use org.quartz.SimpleTrigger. 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: SimpleTriggerMixinTest.java    From quartz-redis-jobstore with Apache License 2.0 6 votes vote down vote up
@Test
public void serialization(){
    SimpleTrigger trigger = TriggerBuilder.newTrigger()
            .forJob("testJob", "testGroup")
            .withIdentity("testTrigger", "testTriggerGroup")
            .usingJobData("timeout", 5)
            .withDescription("A description!")
            .withSchedule(SimpleScheduleBuilder.repeatHourlyForever())
            .build();

    Map<String, String> triggerMap = mapper.convertValue(trigger, new TypeReference<HashMap<String, String>>() {});

    assertThat(triggerMap, hasKey("name"));
    assertEquals("testTrigger", triggerMap.get("name"));
    assertThat(triggerMap, hasKey("group"));
    assertEquals("testTriggerGroup", triggerMap.get("group"));
    assertThat(triggerMap, hasKey("jobName"));
    assertEquals("testJob", triggerMap.get("jobName"));

    SimpleTriggerImpl simpleTrigger = mapper.convertValue(triggerMap, SimpleTriggerImpl.class);

    assertEquals(trigger.getKey().getName(), simpleTrigger.getKey().getName());
    assertEquals(trigger.getKey().getGroup(), simpleTrigger.getKey().getGroup());
    assertEquals(trigger.getStartTime(), simpleTrigger.getStartTime());
    assertEquals(trigger.getRepeatInterval(), simpleTrigger.getRepeatInterval());
}
 
Example #2
Source File: ScheduleManager.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
private Trigger createTrigger(String name, String group, int mode,
        long interval) {

    SimpleTrigger trigger = newTrigger()
            .withIdentity(name, "default")
            .forJob(name, group)
            .startAt(new Date())
            .endAt(null)
            .withSchedule(simpleSchedule()
                    .withRepeatCount(mode)
                    .withIntervalInMilliseconds(interval))
            .build();
    if (trigger instanceof MutableTrigger) {
        MutableTrigger mtrigger = (MutableTrigger) trigger;
        mtrigger.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT);
        return mtrigger;
    }
    else {
        log.error("Cannot set MisfireInstruction since trigger is not instance of MutableTrigger: " + trigger);
    }
    return trigger;
}
 
Example #3
Source File: TimerService.java    From teku with Apache License 2.0 6 votes vote down vote up
@Override
public SafeFuture<?> doStart() {
  try {
    SimpleTrigger trigger =
        newTrigger()
            .withIdentity("TimerTrigger")
            .startAt(DateBuilder.futureDate(START_DELAY, DateBuilder.IntervalUnit.MILLISECOND))
            .withSchedule(simpleSchedule().withIntervalInMilliseconds(interval).repeatForever())
            .build();
    sched.scheduleJob(job, trigger);
    sched.start();
    return SafeFuture.COMPLETE;
  } catch (SchedulerException e) {
    return SafeFuture.failedFuture(new RuntimeException("TimerService failed to start", e));
  }
}
 
Example #4
Source File: GCalPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Schedules new quartz scheduler job for uploading calendar entries to Google
 */
private void scheduleUploadJob() {
    try {
        scheduler = StdSchedulerFactory.getDefaultScheduler();
        JobDetail job = newJob(SynchronizationJob.class).withIdentity("Upload_GCal-Entries", GCAL_SCHEDULER_GROUP)
                .build();

        SimpleTrigger trigger = newTrigger().withIdentity("Upload_GCal-Entries", GCAL_SCHEDULER_GROUP)
                .withSchedule(repeatSecondlyForever(uploadInterval)).build();

        scheduler.scheduleJob(job, trigger);
        logger.debug("Scheduled Google Calendar Upload-Job with interval '{}'", uploadInterval);
    } catch (SchedulerException e) {
        logger.warn("Could not create Google Calendar Upload-Job: {}", e.getMessage());
    }
}
 
Example #5
Source File: TriggerUtils.java    From quartz-glass with Apache License 2.0 6 votes vote down vote up
public static String getPlanification(Trigger trigger) {
    if (trigger instanceof CronTrigger) {
        CronTrigger cronTrigger = (CronTrigger) trigger;

        try {
            return CronExpressionDescriptor.getDescription(cronTrigger.getCronExpression())
                    + "<br/>(" + cronTrigger.getCronExpression() + ")";
        } catch (ParseException e) {
            return cronTrigger.getCronExpression();
        }
    }

    SimpleTrigger simpleTrigger = (SimpleTrigger) trigger;

    return getPlanification(simpleTrigger.getRepeatCount(), simpleTrigger.getRepeatInterval());
}
 
Example #6
Source File: ScheduleManager.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Will create/schedule a trigger for the passed in indexName.
 * Note: Only one trigger per indexName is allowed, if subsequent calls
 * are made before the current trigger finishes completion, this request
 * will be dropped.
 * @param indexName
 * @return
 */
public boolean triggerIndexTask(String indexName) {
    if (!isSupported(indexName)) {
        log.info(indexName + " is not a supported for scheduler modifications.");
        return false;
    }
    // Define a Trigger that will fire "now" and associate it with the existing job
    Trigger trigger = new SimpleTrigger("immediateTrigger-" + indexName,
            "group1", new Date());
    trigger.setJobName(indexName);
    trigger.setJobGroup(updateIndexGroupName);
    try {
        // Schedule the trigger
        log.info("Scheduling trigger: " + trigger);
        scheduler.scheduleJob(trigger);
    }
    catch (SchedulerException e) {
        log.warn("Scheduling trigger: " + trigger + " failed.");
        log.warn("Exception was caught: ",  e);
        return false;
    }
    return true;
}
 
Example #7
Source File: JobServiceImpl.java    From spring-boot-quartz-demo with MIT License 6 votes vote down vote up
/**
 * Schedule a job by jobName at given date.
 */
@Override
public boolean scheduleCronJob(String jobName, Class<? extends QuartzJobBean> jobClass, Date date, String cronExpression) {
	System.out.println("Request received to scheduleJob");

	String jobKey = jobName;
	String groupKey = "SampleGroup";	
	String triggerKey = jobName;		

	JobDetail jobDetail = JobUtil.createJob(jobClass, false, context, jobKey, groupKey);

	System.out.println("creating trigger for key :"+jobKey + " at date :"+date);
	Trigger cronTriggerBean = JobUtil.createCronTrigger(triggerKey, date, cronExpression, SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);

	try {
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		Date dt = scheduler.scheduleJob(jobDetail, cronTriggerBean);
		System.out.println("Job with key jobKey :"+jobKey+ " and group :"+groupKey+ " scheduled successfully for date :"+dt);
		return true;
	} catch (SchedulerException e) {
		System.out.println("SchedulerException while scheduling job with key :"+jobKey + " message :"+e.getMessage());
		e.printStackTrace();
	}

	return false;
}
 
Example #8
Source File: JobServiceImpl.java    From spring-boot-quartz-demo with MIT License 6 votes vote down vote up
/**
 * Update one time scheduled job.
 */
@Override
public boolean updateOneTimeJob(String jobName, Date date) {
	System.out.println("Request received for updating one time job.");

	String jobKey = jobName;

	System.out.println("Parameters received for updating one time job : jobKey :"+jobKey + ", date: "+date);
	try {
		//Trigger newTrigger = JobUtil.createSingleTrigger(jobKey, date, SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT);
		Trigger newTrigger = JobUtil.createSingleTrigger(jobKey, date, SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);

		Date dt = schedulerFactoryBean.getScheduler().rescheduleJob(TriggerKey.triggerKey(jobKey), newTrigger);
		System.out.println("Trigger associated with jobKey :"+jobKey+ " rescheduled successfully for date :"+dt);
		return true;
	} catch ( Exception e ) {
		System.out.println("SchedulerException while updating one time job with key :"+jobKey + " message :"+e.getMessage());
		e.printStackTrace();
		return false;
	}
}
 
Example #9
Source File: JobServiceImpl.java    From spring-boot-quartz-demo with MIT License 6 votes vote down vote up
/**
 * Update scheduled cron job.
 */
@Override
public boolean updateCronJob(String jobName, Date date, String cronExpression) {
	System.out.println("Request received for updating cron job.");

	String jobKey = jobName;

	System.out.println("Parameters received for updating cron job : jobKey :"+jobKey + ", date: "+date);
	try {
		//Trigger newTrigger = JobUtil.createSingleTrigger(jobKey, date, SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT);
		Trigger newTrigger = JobUtil.createCronTrigger(jobKey, date, cronExpression, SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);

		Date dt = schedulerFactoryBean.getScheduler().rescheduleJob(TriggerKey.triggerKey(jobKey), newTrigger);
		System.out.println("Trigger associated with jobKey :"+jobKey+ " rescheduled successfully for date :"+dt);
		return true;
	} catch ( Exception e ) {
		System.out.println("SchedulerException while updating cron job with key :"+jobKey + " message :"+e.getMessage());
		e.printStackTrace();
		return false;
	}
}
 
Example #10
Source File: StdJDBCDelegate.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Update the simple trigger data.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param trigger
 *          the trigger to insert
 * @return the number of rows updated
 */
public int updateSimpleTrigger(Connection conn, SimpleTrigger trigger)
    throws SQLException {
    PreparedStatement ps = null;

    try {
        ps = conn.prepareStatement(rtp(UPDATE_SIMPLE_TRIGGER));

        ps.setInt(1, trigger.getRepeatCount());
        ps.setBigDecimal(2, new BigDecimal(String.valueOf(trigger
                .getRepeatInterval())));
        ps.setInt(3, trigger.getTimesTriggered());
        ps.setString(4, trigger.getName());
        ps.setString(5, trigger.getGroup());

        return ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }
}
 
Example #11
Source File: SimpleTriggerPersistenceDelegate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public int insertExtendedTriggerProperties(Connection conn, OperableTrigger trigger, String state, JobDetail jobDetail) throws SQLException, IOException {

        SimpleTrigger simpleTrigger = (SimpleTrigger)trigger;
        
        PreparedStatement ps = null;
        
        try {
            ps = conn.prepareStatement(Util.rtp(INSERT_SIMPLE_TRIGGER, tablePrefix, schedNameLiteral));
            ps.setString(1, trigger.getKey().getName());
            ps.setString(2, trigger.getKey().getGroup());
            ps.setInt(3, simpleTrigger.getRepeatCount());
            ps.setBigDecimal(4, new BigDecimal(String.valueOf(simpleTrigger.getRepeatInterval())));
            ps.setInt(5, simpleTrigger.getTimesTriggered());

            return ps.executeUpdate();
        } finally {
            Util.closeStatement(ps);
        }
    }
 
Example #12
Source File: SimpleTriggerPersistenceDelegate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public int updateExtendedTriggerProperties(Connection conn, OperableTrigger trigger, String state, JobDetail jobDetail) throws SQLException, IOException {

        SimpleTrigger simpleTrigger = (SimpleTrigger)trigger;
        
        PreparedStatement ps = null;

        try {
            ps = conn.prepareStatement(Util.rtp(UPDATE_SIMPLE_TRIGGER, tablePrefix, schedNameLiteral));

            ps.setInt(1, simpleTrigger.getRepeatCount());
            ps.setBigDecimal(2, new BigDecimal(String.valueOf(simpleTrigger.getRepeatInterval())));
            ps.setInt(3, simpleTrigger.getTimesTriggered());
            ps.setString(4, simpleTrigger.getKey().getName());
            ps.setString(5, simpleTrigger.getKey().getGroup());

            return ps.executeUpdate();
        } finally {
            Util.closeStatement(ps);
        }
    }
 
Example #13
Source File: SimpleTriggerImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a {@link ScheduleBuilder} that is configured to produce a 
 * schedule identical to this trigger's schedule.
 * 
 * @see #getTriggerBuilder()
 */
@Override
public ScheduleBuilder<SimpleTrigger> getScheduleBuilder() {
    
    SimpleScheduleBuilder sb = SimpleScheduleBuilder.simpleSchedule()
    .withIntervalInMilliseconds(getRepeatInterval())
    .withRepeatCount(getRepeatCount());
    
    switch(getMisfireInstruction()) {
        case MISFIRE_INSTRUCTION_FIRE_NOW : sb.withMisfireHandlingInstructionFireNow();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT : sb.withMisfireHandlingInstructionNextWithExistingCount();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT : sb.withMisfireHandlingInstructionNextWithRemainingCount();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT : sb.withMisfireHandlingInstructionNowWithExistingCount();
        break;
        case MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT : sb.withMisfireHandlingInstructionNowWithRemainingCount();
        break;
    }
    
    return sb;
}
 
Example #14
Source File: Db4oPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Schedules new quartz scheduler jobs for committing transactions and
 * backing up the database
 */
private void scheduleJob() {
    try {
        Scheduler sched = StdSchedulerFactory.getDefaultScheduler();

        // schedule commit-job
        JobDetail job = newJob(CommitJob.class).withIdentity("Commit_Transaction", SCHEDULER_GROUP).build();

        SimpleTrigger trigger = newTrigger().withIdentity("Commit_Transaction", SCHEDULER_GROUP)
                .withSchedule(repeatSecondlyForever(commitInterval)).build();

        sched.scheduleJob(job, trigger);
        logger.debug("Scheduled Commit-Job with interval {}sec.", commitInterval);

        // schedule backup-job
        JobDetail backupJob = newJob(BackupJob.class).withIdentity("Backup_DB", SCHEDULER_GROUP).build();

        CronTrigger backupTrigger = newTrigger().withIdentity("Backup_DB", SCHEDULER_GROUP)
                .withSchedule(CronScheduleBuilder.cronSchedule(backupInterval)).build();

        sched.scheduleJob(backupJob, backupTrigger);
        logger.debug("Scheduled Backup-Job with cron expression '{}'", backupInterval);
    } catch (SchedulerException e) {
        logger.warn("Could not create Job: {}", e.getMessage());
    }
}
 
Example #15
Source File: StdJDBCDelegate.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Insert the simple trigger data.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param trigger
 *          the trigger to insert
 * @return the number of rows inserted
 */
public int insertSimpleTrigger(Connection conn, SimpleTrigger trigger)
    throws SQLException {
    PreparedStatement ps = null;

    try {
        ps = conn.prepareStatement(rtp(INSERT_SIMPLE_TRIGGER));
        ps.setString(1, trigger.getName());
        ps.setString(2, trigger.getGroup());
        ps.setInt(3, trigger.getRepeatCount());
        ps.setBigDecimal(4, new BigDecimal(String.valueOf(trigger
                .getRepeatInterval())));
        ps.setInt(5, trigger.getTimesTriggered());

        return ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }
}
 
Example #16
Source File: SchedulerUtil.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/**
 * Schedule the harvest completion to run after a specified delay to allow the 
    * harvester to release all its resources or after a failure to contace the 
    * core or the digital asset store
 * @param aHarvestName the name of the harvest job
 * @param aFailueStep the step that the completion failed at
 * @param aMessageSent a flag to indicated that the failure notification has been sent
 * @param aRetries the number of retries attempted
 * @throws SchedulerException thrown if there is a problem scheduling the quartz job
 */
public static final void scheduleHarvestCompleteJob(String aHarvestName, int aFailueStep, boolean aMessageSent, int aRetries) throws SchedulerException {
	ApplicationContext context = ApplicationContextFactory.getWebApplicationContext();
	Scheduler scheduler = (Scheduler) context.getBean(Constants.BEAN_SCHEDULER_FACTORY);
	HarvestCompleteConfig hcc = (HarvestCompleteConfig) context.getBean(Constants.BEAN_HARVEST_COMPLETE_CONFIG);
    
       JobDetail job = new JobDetail(JOB_NAME_COMPLETE + SEPERATOR + aHarvestName + SEPERATOR + aRetries, JOB_GROUP_COMPLETE + SEPERATOR + aHarvestName, HarvestCompleteJob.class);
       JobDataMap jdm = new JobDataMap();
       jdm.put(HarvestCompleteJob.PARAM_JOB_NAME, aHarvestName);
       jdm.put(HarvestCompleteJob.PARAM_FAILURE_STEP, new Integer(aFailueStep));
       jdm.put(HarvestCompleteJob.PARAM_MSG_SENT, new Boolean(aMessageSent));
       jdm.put(HarvestCompleteJob.PARAM_RETRIES, new Integer(aRetries));
       job.setJobDataMap(jdm);

       // Set the complete job to run xx seconds after we get the notification
       Calendar cal = Calendar.getInstance();
       if (aRetries == 0) {
       	cal.add(Calendar.SECOND, hcc.getWaitOnCompleteSeconds());
       }
       else if (aRetries < hcc.getLevelRetryBand()) {
       	cal.add(Calendar.SECOND, hcc.getWaitOnFailureLevelOneSecs());
       }
       else {
       	cal.add(Calendar.SECOND, hcc.getWaitOnFailureLevelTwoSecs());
       }
               
       Trigger trigger = new SimpleTrigger(TRG_NAME_COMPLETE + SEPERATOR + aHarvestName + SEPERATOR + aRetries, TRG_GROUP_COMPLETE + SEPERATOR + aHarvestName, cal.getTime());                       
       scheduler.scheduleJob(job, trigger);
}
 
Example #17
Source File: AssetExtractionCleanupJob.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Bean
public SimpleTriggerFactoryBean triggerAssetExtractionCleanup(@Qualifier("jobDetailAssetExtractionCleanup") JobDetail job) {
    SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
    trigger.setJobDetail(job);
    trigger.setRepeatInterval(Duration.ofMinutes(5).toMillis());
    trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
    return trigger;
}
 
Example #18
Source File: PluralFormUpdaterJob.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Bean
SimpleTriggerFactoryBean triggerPluralFormUpdater(@Qualifier("jobDetailPluralFromUpdater") JobDetail job) {
    SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
    trigger.setJobDetail(job);
    trigger.setRepeatInterval(10000);
    trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
    return trigger;
}
 
Example #19
Source File: ShowScheduler.java    From iaf with Apache License 2.0 5 votes vote down vote up
private List<Map<String, Object>> getJobTriggers(List<? extends Trigger> triggers) throws ApiException {
	List<Map<String, Object>> jobTriggers = new ArrayList<Map<String, Object>>();

	for (Trigger trigger : triggers) {
		Map<String, Object> triggerDetails = new HashMap<String, Object>();

		TriggerKey triggerKey = trigger.getKey();
		triggerDetails.put("fullName", triggerKey.getGroup() + "." + triggerKey.getName());
		triggerDetails.put("name", triggerKey.getName());
		triggerDetails.put("calendarName", trigger.getCalendarName());

		putDateProperty(triggerDetails, "endTime", trigger.getEndTime());
		putDateProperty(triggerDetails, "finalFireTime", trigger.getFinalFireTime());
		putDateProperty(triggerDetails, "nextFireTime", trigger.getNextFireTime());
		putDateProperty(triggerDetails, "previousFireTime", trigger.getPreviousFireTime());
		putDateProperty(triggerDetails, "startTime", trigger.getStartTime());

		triggerDetails.put("misfireInstruction", trigger.getMisfireInstruction());

		if (trigger instanceof CronTrigger) {
			triggerDetails.put("triggerType", "cron");
			triggerDetails.put("cronExpression", ((CronTrigger) trigger).getCronExpression());
		} else if (trigger instanceof SimpleTrigger) {
			triggerDetails.put("triggerType", "simple");
			triggerDetails.put("repeatInterval", ((SimpleTrigger) trigger).getRepeatInterval());
		} else {
			triggerDetails.put("triggerType", "unknown");
		}

		jobTriggers.add(triggerDetails);
	}

	return jobTriggers;
}
 
Example #20
Source File: PollableTaskCleanupJob.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Bean
public SimpleTriggerFactoryBean triggerPollableTaskCleanup(@Qualifier("jobDetailPollableTaskCleanup") JobDetail job) {
    SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
    trigger.setJobDetail(job);
    trigger.setRepeatInterval(REPEAT_INTERVAL);
    trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
    return trigger;
}
 
Example #21
Source File: TestContextConfiguration11.java    From spring-boot-starter-quartz with Apache License 2.0 5 votes vote down vote up
@Bean(name="simpleJobTrigger2")
public SimpleTriggerFactoryBean createSimpleTrigger2(@Qualifier("simpleJobDetail") JobDetail jobDetail) {
	Map<String, Object> map = new HashMap<>(1);
	map.put("myKey", "myValue");
	return QuartzUtils.createSimpleTrigger(jobDetail, "STName2", "STGroup2", "STDesc2", 10000L, 30000L,
			SimpleTrigger.REPEAT_INDEFINITELY,
			SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT, map, 1000);
}
 
Example #22
Source File: TestJobGlobalListener.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/** Test.
 * @throws SchedulerException e
 * @throws InterruptedException e */
@Test
public void testJobGlobalListener() throws SchedulerException, InterruptedException {
	final Counter jobCounter = JobGlobalListener.getJobCounter();
	jobCounter.clear();
	jobCounter.setDisplayed(true);
	// job quartz
	JobGlobalListener.initJobGlobalListener();

	//Grab the Scheduler instance from the Factory
	final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

	try {
		// and start it off
		scheduler.start();

		final Random random = new Random();
		// on lance 10 jobs pour être à peu près sûr qu'il y en a un qui fait une erreur
		// (aléatoirement il y en a 2/10 qui font une erreur)
		for (int i = 0; i < 10; i++) {
			//Define job instance
			final JobDetail job = new JobDetail("job" + random.nextInt(), null,
					JobTestImpl.class);

			//Define a Trigger that will fire "now"
			final Trigger trigger = new SimpleTrigger("trigger" + random.nextInt(), null,
					new Date());
			//Schedule the job with the trigger
			scheduler.scheduleJob(job, trigger);
		}

		// JobTestImpl fait un sleep de 2s au plus, donc on attend les jobs pour les compter
		Thread.sleep(3000);

		assertTrue("requestsCount", jobCounter.getRequestsCount() > 0);
	} finally {
		scheduler.shutdown();
		JobGlobalListener.destroyJobGlobalListener();
	}
}
 
Example #23
Source File: BlobStorageConfiguration.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Profile("!disablescheduling")
@Bean
public SimpleTriggerFactoryBean triggerExpiringBlobCleanup(@Qualifier("jobDetailDatabaseBlobStorageCleanupJob") JobDetail job) {
    logger.info("Configure jobDetailDatabaseBlobStorageCleanupJob");
    SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
    trigger.setJobDetail(job);
    trigger.setRepeatInterval(Duration.ofMinutes(5).toMillis());
    trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
    return trigger;
}
 
Example #24
Source File: TestContextConfiguration4.java    From spring-boot-starter-quartz with Apache License 2.0 5 votes vote down vote up
@Bean(name="simpleJobTrigger2")
public SimpleTriggerFactoryBean createSimpleTrigger2(@Qualifier("simpleJobDetail") JobDetail jobDetail) {
	Map<String, Object> map = new HashMap<>(1);
	map.put("myKey", "myValue");
	return QuartzUtils.createSimpleTrigger(jobDetail, "STName2", "STGroup2", "STDesc2", 10000L, 30000L,
			SimpleTrigger.REPEAT_INDEFINITELY,
			SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT, map, 1000);
}
 
Example #25
Source File: Test.java    From fixflow with Apache License 2.0 5 votes vote down vote up
public void task() throws SchedulerException {
	SchedulerFactory schedulerFactory = QuartzUtil.createSchedulerFactory();
	Scheduler scheduler = QuartzUtil.getScheduler(schedulerFactory);
	Trigger tg = QuartzUtil.getTrigger(scheduler, "mytrigger");
	((SimpleTrigger)tg).getRepeatCount();
       // reschedule the job
       scheduler.rescheduleJob(new TriggerKey("mytrigger"), tg);
}
 
Example #26
Source File: SchedulerConfig.java    From quartz-manager with Apache License 2.0 5 votes vote down vote up
private static SimpleTriggerFactoryBean createTrigger(JobDetail jobDetail, long pollFrequencyMs,
		int repeatCount) {
	SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
	factoryBean.setJobDetail(jobDetail);
	factoryBean.setStartDelay(3000L);
	factoryBean.setRepeatInterval(pollFrequencyMs);
	factoryBean.setRepeatCount(repeatCount);
	factoryBean
	.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT);// in case of misfire, ignore all missed triggers and continue
	return factoryBean;
}
 
Example #27
Source File: SchedulerController.java    From quartz-manager with Apache License 2.0 5 votes vote down vote up
@GetMapping("/config")
public SchedulerConfigParam getConfig() {
	log.debug("SCHEDULER - GET CONFIG params");
	SimpleTrigger simpleTrigger = (SimpleTrigger) triggerMonitor.getTrigger();

	int maxCount = simpleTrigger.getRepeatCount() + 1;
	long triggersPerDay = fromMillsIntervalToTriggerPerDay(simpleTrigger.getRepeatInterval());

	return new SchedulerConfigParam(triggersPerDay, maxCount);
}
 
Example #28
Source File: SchedulerController.java    From quartz-manager with Apache License 2.0 5 votes vote down vote up
@PostMapping("/config")
public SchedulerConfigParam postConfig(@RequestBody SchedulerConfigParam config) throws SchedulerException {
	log.info("SCHEDULER - NEW CONFIG {}", config);
	SimpleTrigger trigger = (SimpleTrigger) triggerMonitor.getTrigger();

	TriggerBuilder<SimpleTrigger> triggerBuilder = trigger.getTriggerBuilder();

	int intervalInMills = fromTriggerPerDayToMillsInterval(config.getTriggerPerDay());
	Trigger newTrigger = triggerBuilder.withSchedule(SimpleScheduleBuilder.simpleSchedule()
			.withIntervalInMilliseconds(intervalInMills).withRepeatCount(config.getMaxCount() - 1)).build();

	scheduler.rescheduleJob(triggerMonitor.getTrigger().getKey(), newTrigger);
	triggerMonitor.setTrigger(newTrigger);
	return config;
}
 
Example #29
Source File: WebSocketProgressNotifier.java    From quartz-manager with Apache License 2.0 5 votes vote down vote up
@Override
public void send() throws SchedulerException {
	TriggerStatus currTriggerStatus = new TriggerStatus();

	Trigger trigger = scheduler.getTrigger(triggerMonitor.getTrigger().getKey());
	currTriggerStatus.setFinalFireTime(trigger.getFinalFireTime());
	currTriggerStatus.setNextFireTime(trigger.getNextFireTime());
	currTriggerStatus.setPreviousFireTime(trigger.getPreviousFireTime());

	int timesTriggered = 0;
	int repeatCount = 0;

	if (trigger instanceof SimpleTrigger) {
		SimpleTrigger simpleTrigger = (SimpleTrigger) trigger;
		timesTriggered = simpleTrigger.getTimesTriggered();
		repeatCount = simpleTrigger.getRepeatCount();
	} else if (trigger instanceof DailyTimeIntervalTrigger) {
		DailyTimeIntervalTrigger dailyTrigger = (DailyTimeIntervalTrigger) trigger;
		timesTriggered = dailyTrigger.getTimesTriggered();
		repeatCount = dailyTrigger.getRepeatCount();
	}

	Trigger jobTrigger = triggerMonitor.getTrigger();
	if (jobTrigger != null && jobTrigger.getJobKey() != null) {
		currTriggerStatus.setJobKey(jobTrigger.getJobKey().getName());
		currTriggerStatus.setJobClass(jobTrigger.getClass().getSimpleName());
		currTriggerStatus.setTimesTriggered(timesTriggered);
		currTriggerStatus.setRepeatCount(repeatCount + 1);
	}

	messagingTemplate.convertAndSend("/topic/progress", currTriggerStatus);
}
 
Example #30
Source File: SchedulerUtil.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/**
 * Schedule the harvest completion to run after a specified delay to allow the 
    * harvester to release all its resources or after a failure to contace the 
    * core or the digital asset store
 * @param aHarvestName the name of the harvest job
 * @param aFailueStep the step that the completion failed at
 * @param aMessageSent a flag to indicated that the failure notification has been sent
 * @param aRetries the number of retries attempted
 * @throws SchedulerException thrown if there is a problem scheduling the quartz job
 */
public static final void scheduleHarvestCompleteJob(String aHarvestName, int aFailueStep, boolean aMessageSent, int aRetries) throws SchedulerException {
	ApplicationContext context = ApplicationContextFactory.getWebApplicationContext();
	Scheduler scheduler = (Scheduler) context.getBean(Constants.BEAN_SCHEDULER_FACTORY);
	HarvestCompleteConfig hcc = (HarvestCompleteConfig) context.getBean(Constants.BEAN_HARVEST_COMPLETE_CONFIG);
    
       JobDetail job = new JobDetail(JOB_NAME_COMPLETE + SEPERATOR + aHarvestName + SEPERATOR + aRetries, JOB_GROUP_COMPLETE + SEPERATOR + aHarvestName, HarvestCompleteJob.class);
       JobDataMap jdm = new JobDataMap();
       jdm.put(HarvestCompleteJob.PARAM_JOB_NAME, aHarvestName);
       jdm.put(HarvestCompleteJob.PARAM_FAILURE_STEP, new Integer(aFailueStep));
       jdm.put(HarvestCompleteJob.PARAM_MSG_SENT, new Boolean(aMessageSent));
       jdm.put(HarvestCompleteJob.PARAM_RETRIES, new Integer(aRetries));
       job.setJobDataMap(jdm);

       // Set the complete job to run xx seconds after we get the notification
       Calendar cal = Calendar.getInstance();
       if (aRetries == 0) {
       	cal.add(Calendar.SECOND, hcc.getWaitOnCompleteSeconds());
       }
       else if (aRetries < hcc.getLevelRetryBand()) {
       	cal.add(Calendar.SECOND, hcc.getWaitOnFailureLevelOneSecs());
       }
       else {
       	cal.add(Calendar.SECOND, hcc.getWaitOnFailureLevelTwoSecs());
       }
               
       Trigger trigger = new SimpleTrigger(TRG_NAME_COMPLETE + SEPERATOR + aHarvestName + SEPERATOR + aRetries, TRG_GROUP_COMPLETE + SEPERATOR + aHarvestName, cal.getTime());                       
       scheduler.scheduleJob(job, trigger);
}