com.cronutils.model.definition.CronDefinitionBuilder Java Examples

The following examples show how to use com.cronutils.model.definition.CronDefinitionBuilder. 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: Issue305Test.java    From cron-utils with Apache License 2.0 8 votes vote down vote up
@Test
public void testIssue305(){
    CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);
    CronParser parser = new CronParser(cronDefinition);
    Cron cron = parser.parse("0 0 0 15 8 ? 2015-2099/2");

    ExecutionTime executionTime = ExecutionTime.forCron(cron);
    Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(ZonedDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneId.of("UTC")));
    Set<ZonedDateTime> dates = new LinkedHashSet<>();
    while (!nextExecution.get().isAfter(ZonedDateTime.of(2020, 12, 31, 0, 0, 0, 0, ZoneId.of("UTC")))) {
        dates.add(nextExecution.get());
        nextExecution = executionTime.nextExecution(nextExecution.get());
    }
    Set<Integer> years = dates.stream().map(d->d.getYear()).collect(Collectors.toSet());
    Set<Integer> expectedYears = new HashSet<>();
    expectedYears.add(2015);
    expectedYears.add(2017);
    expectedYears.add(2019);
    assertEquals(expectedYears, years);
}
 
Example #2
Source File: ExecutionTimeQuartzIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #124:
 * https://github.com/jmrozanec/cron-utils/issues/124
 * Reported case: next execution time is set improperly
 * Potential duplicate: https://github.com/jmrozanec/cron-utils/issues/123
 */
@Test
public void testNextExecutionTimeProperlySet2() {
    final CronParser quartzCronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
    final String quartzCronExpression2 = "0 3/27 10-14 * * ? *";
    final Cron parsedQuartzCronExpression = quartzCronParser.parse(quartzCronExpression2);

    final ExecutionTime executionTime = ExecutionTime.forCron(parsedQuartzCronExpression);

    final ZonedDateTime zonedDateTime = LocalDateTime.of(2016, 1, 1, 10, 0, 0, 0).atZone(ZoneOffset.UTC);

    final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(zonedDateTime);
    if (nextExecution.isPresent()) {
        final ZonedDateTime nextExecutionTime = nextExecution.get();
        assertEquals("2016-01-01T10:03Z", nextExecutionTime.toString());
    } else {
        fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #3
Source File: ExecutionTimeQuartzIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #123:
 * https://github.com/jmrozanec/cron-utils/issues/123
 * Reported case: next execution time is set improperly
 * Potential duplicate: https://github.com/jmrozanec/cron-utils/issues/124
 */
@Test
public void testNextExecutionTimeProperlySet() {
    final CronParser quartzCronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
    final String quartzCronExpression2 = "0 5/15 * * * ? *";
    final Cron parsedQuartzCronExpression = quartzCronParser.parse(quartzCronExpression2);

    final ExecutionTime executionTime = ExecutionTime.forCron(parsedQuartzCronExpression);

    final ZonedDateTime zonedDateTime = LocalDateTime.of(2016, 7, 30, 15, 0, 0, 527).atZone(ZoneOffset.UTC);
    final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(zonedDateTime);
    final Optional<ZonedDateTime> lastExecution = executionTime.lastExecution(zonedDateTime);
    if (nextExecution.isPresent() && lastExecution.isPresent()) {
        final ZonedDateTime nextExecutionTime = nextExecution.get();
        final ZonedDateTime lastExecutionTime = lastExecution.get();

        assertEquals("2016-07-30T14:50Z", lastExecutionTime.toString());
        assertEquals("2016-07-30T15:05Z", nextExecutionTime.toString());
    } else {
        fail(ASSERTED_EXECUTION_NOT_PRESENT);
    }
}
 
Example #4
Source File: ExecutionTimeCustomDefinitionIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Test for issue #38
 * https://github.com/jmrozanec/cron-utils/issues/38
 * Reported case: lastExecution and nextExecution do not work properly
 * Expected: should return expected date
 */
@Test
public void testCronExpressionEveryTwoHoursSlash() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.defineCron()
            .withSeconds().and()
            .withMinutes().and()
            .withHours().and()
            .withDayOfMonth().and()
            .withMonth().and()
            .withDayOfWeek().withValidRange(0, 7).withMondayDoWValue(1).withIntMapping(7, 0).and()
            .instance();

    final CronParser parser = new CronParser(cronDefinition);
    final Cron cron = parser.parse("0 0 /2 * * *");
    final ZonedDateTime startDateTime = ZonedDateTime.parse("2015-08-28T12:05:14.000-03:00");

    final Optional<ZonedDateTime> nextExecution = ExecutionTime.forCron(cron).nextExecution(startDateTime);
    if (nextExecution.isPresent()) {
        assertTrue(ZonedDateTime.parse("2015-08-28T14:00:00.000-03:00").compareTo(nextExecution.get()) == 0);
    } else {
        fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #5
Source File: CronPolicy.java    From kafka-connect-fs with Apache License 2.0 6 votes vote down vote up
@Override
protected void configPolicy(Map<String, Object> customConfigs) {
    try {
        if (customConfigs.get(CRON_POLICY_END_DATE) != null &&
                !customConfigs.get(CRON_POLICY_END_DATE).toString().equals("")) {
            endDate = Date.from(LocalDateTime.parse(customConfigs.get(CRON_POLICY_END_DATE).toString().trim())
                    .atZone(ZoneId.systemDefault()).toInstant());
        }
        executionTime = ExecutionTime.forCron(
                new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ))
                        .parse(customConfigs.get(CRON_POLICY_EXPRESSION).toString())
        );
    } catch (DateTimeException dte) {
        throw new ConfigException(CRON_POLICY_END_DATE + " property must have a proper value. Got: '" +
                customConfigs.get(CRON_POLICY_END_DATE) + "'.");
    } catch (IllegalArgumentException iae) {
        throw new ConfigException(CRON_POLICY_EXPRESSION + " property must have a proper value. Got: '" +
                customConfigs.get(CRON_POLICY_EXPRESSION) + "'.");
    }
}
 
Example #6
Source File: CronServiceTest.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Test
public void should_get_exec_time_from_crontab() throws InterruptedException {
    CronDefinition definition = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
    CronParser parser = new CronParser(definition);

    Cron cron = parser.parse("* * * * *");
    ExecutionTime executionTime = ExecutionTime.forCron(cron);
    Assert.assertNotNull(executionTime);

    ZonedDateTime now = ZonedDateTime.now();
    long seconds = executionTime.timeToNextExecution(now).get().getSeconds();
    log.info("--- {} ----", seconds);

    ObjectWrapper<Boolean> result = new ObjectWrapper<>(false);
    CountDownLatch counter = new CountDownLatch(1);

    service.schedule(() -> {
        result.setValue(true);
        counter.countDown();
    }, seconds, TimeUnit.SECONDS);

    counter.await();
    Assert.assertTrue(result.getValue());
}
 
Example #7
Source File: TimerTaskExecutorProvider.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
public static Flux<ZonedDateTime> getLastExecuteTimes(String cronExpression, Date from, long times) {
    return Flux.create(sink -> {
        CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
        Cron cron = parser.parse(cronExpression);
        ExecutionTime executionTime = ExecutionTime.forCron(cron);
        ZonedDateTime dateTime = ZonedDateTime.ofInstant(from.toInstant(), ZoneId.systemDefault());

        for (long i = 0; i < times; i++) {
            dateTime = executionTime.nextExecution(dateTime)
                .orElse(null);
            if (dateTime != null) {
                sink.next(dateTime);
            } else {
                break;
            }
        }
        sink.complete();


    });
}
 
Example #8
Source File: MappingOptionalFieldsTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testMappingOptionalFields() {
    CronDefinition cronDefinition = CronDefinitionBuilder.defineCron()
            .withMinutes().withStrictRange().withValidRange(0, 60).and()
            .withHours().withStrictRange().and()
            .withDayOfMonth().supportsL().withStrictRange().and()
            .withMonth().withStrictRange().and()
            .withDayOfWeek().withValidRange(0, 7).withMondayDoWValue(1).withIntMapping(7, 0).supportsHash().supportsL().withStrictRange().and()
            .withYear().optional().and()
            .instance();

    final CronDefinition quartzDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);

    CronParser parser = new CronParser(quartzDefinition);
    CronMapper mapper = new CronMapper(quartzDefinition, cronDefinition, cron -> cron);


    final String expected = "0 9-18 * * 0-2";
    final String expression = "5 0 9-18 ? * 1-3";
    final String mapping = mapper.map(parser.parse(expression)).asString();
    assertEquals(String.format("Expected [%s] but got [%s]", expected, mapping), expected, mapping);
}
 
Example #9
Source File: ExecutionTimeCustomDefinitionIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * A CronDefinition with only 3 required fields is legal to instantiate, but the parser considers an expression
 * with 4 fields as an error:
 * java.lang.IllegalArgumentException: Cron expression contains 4 parts but we expect one of [6, 7]
 */
@Test
public void testThreeRequiredFieldsSupported() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.defineCron()
            .withSeconds().and()
            .withMinutes().and()
            .withHours().and()
            .withDayOfMonth().supportsL().supportsW().supportsLW().supportsQuestionMark().optional().and()
            .withMonth().optional().and()
            .withDayOfWeek().withValidRange(1, 7).withMondayDoWValue(2).supportsHash().supportsL()
            .supportsQuestionMark().optional().and()
            .withYear().withValidRange(2000, 2099).optional().and()
            .instance();
    final CronParser cronParser = new CronParser(cronDefinition);
    cronParser.parse("* * 4 3");
}
 
Example #10
Source File: ExecutionTimeCustomDefinitionIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #136: Bug exposed at PR #136
 * https://github.com/jmrozanec/cron-utils/pull/136
 * Reported case: when executing isMatch for a given range of dates,
 * if date is invalid, we get an exception, not a boolean as response.
 */
@Test
public void testMatchWorksAsExpectedForCustomCronsWhenPreviousOrNextOccurrenceIsMissing() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.defineCron()
            .withDayOfMonth()
            .supportsL().supportsW()
            .and()
            .withMonth().and()
            .withYear()
            .and().instance();

    final CronParser parser = new CronParser(cronDefinition);
    final Cron cron = parser.parse("05 05 2004");
    final ExecutionTime executionTime = ExecutionTime.forCron(cron);
    ZonedDateTime start = ZonedDateTime.of(2004, 5, 5, 23, 55, 0, 0, ZoneId.of("UTC"));
    final ZonedDateTime end = ZonedDateTime.of(2004, 5, 6, 1, 0, 0, 0, ZoneId.of("UTC"));
    while (start.compareTo(end) < 0) {
        assertTrue(executionTime.isMatch(start) == (start.getDayOfMonth() == 5));
        start = start.plusMinutes(1);
    }
}
 
Example #11
Source File: ExecutionTimeCustomDefinitionIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * A CronDefinition with only 5 required fields is legal to instantiate, but the parser considers an expression
 * with 5 fields as an error:
 * java.lang.IllegalArgumentException: Cron expression contains 4 parts but we expect one of [6, 7]
 */
@Test
public void testFiveRequiredFieldsSupported() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.defineCron()
            .withSeconds().and()
            .withMinutes().and()
            .withHours().and()
            .withDayOfMonth().supportsL().supportsW().supportsLW().supportsQuestionMark().and()
            .withMonth().and()
            .withDayOfWeek().withValidRange(1, 7).withMondayDoWValue(2).supportsHash().supportsL()
            .supportsQuestionMark().optional().and()
            .withYear().withValidRange(2000, 2099).optional().and()
            .instance();
    final CronParser cronParser = new CronParser(cronDefinition);
    cronParser.parse("* * 4 3 *");
}
 
Example #12
Source File: QuartzServiceImpl.java    From spring-batch-quartz-admin with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param jobName
 * @return String
 */
public String getScheduledJobDescription(String jobName) {
    String message = Constants.JOB_IS_NOT_SCHEDULED;
    JobKey jobKey = new JobKey(jobName, Constants.QUARTZ_GROUP);
    try {
        JobDetail jobDetail = schedulerFactory.getScheduler().getJobDetail(jobKey);
        if (null != jobDetail) {
            List<? extends Trigger> triggersOfJob = schedulerFactory.getScheduler().getTriggersOfJob(jobKey);
            if (null != triggersOfJob && !triggersOfJob.isEmpty()) {
                CronTrigger trigger = (CronTrigger) triggersOfJob.get(0);
                String cronExpression = trigger.getCronExpression();
                CronDescriptor descriptor = CronDescriptor.instance(Locale.US);
                CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ));
                message = descriptor.describe(parser.parse(cronExpression));
            }

        }
    } catch (SchedulerException e) {
        BatchAdminLogger.getLogger().error(e.getMessage(), e);
    }
    return message;
}
 
Example #13
Source File: CronParserQuartzIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #154: Quartz Cron Year Pattern is not fully supported - i.e. increments on years are not supported
 * https://github.com/jmrozanec/cron-utils/issues/154
 * Duplicate of #148
 */
@Test
public void supportQuartzCronExpressionIncrementsOnYears() {
    final String[] sampleCronExpressions = {
            "0 0 0 1 * ? 2017/2",
            "0 0 0 1 * ? 2017/3",
            "0 0 0 1 * ? 2017/10",
            "0 0 0 1 * ? 2017-2047/2",
    };

    final CronParser quartzCronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
    for (final String cronExpression : sampleCronExpressions) {
        final Cron quartzCron = quartzCronParser.parse(cronExpression);
        quartzCron.validate();
    }
}
 
Example #14
Source File: ExecutionTimeQuartzIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #142: https://github.com/jmrozanec/cron-utils/pull/142
 * Special Character L for day of week behaves differently in Quartz
 * @throws ParseException in case the CronExpression can not be created
 */
@Test
public void lastDayOfTheWeek() throws ParseException {
    // L (“last”) - If used in the day-of-week field by itself, it simply means “7” or “SAT”.
    final Cron cron = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(QUARTZ)).parse("0 0 0 ? * L *");

    final ZoneId utc = ZoneId.of("UTC");
    final ZonedDateTime date = LocalDate.parse("2016-12-22").atStartOfDay(utc);   // Thursday
    final ZonedDateTime expected = date.plusDays(2);   // Saturday

    final Optional<ZonedDateTime> nextExecution = ExecutionTime.forCron(cron).nextExecution(date);
    if (nextExecution.isPresent()) {
        final ZonedDateTime cronUtilsNextTime = nextExecution.get();// 2016-12-30T00:00:00Z

        final org.quartz.CronExpression cronExpression = new org.quartz.CronExpression(cron.asString());
        cronExpression.setTimeZone(TimeZone.getTimeZone(utc));
        final Date quartzNextTime = cronExpression.getNextValidTimeAfter(Date.from(date.toInstant()));// 2016-12-24T00:00:00Z

        assertEquals(expected.toInstant(), quartzNextTime.toInstant());    // test the reference implementation
        assertEquals(expected.toInstant(), cronUtilsNextTime.toInstant()); // and compare with cronUtils
    } else {
        fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #15
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #38: every 2 min schedule doesn't roll over to next hour.
 */
@Test
public void testEveryTwoMinRollsOverHour() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
    final Cron cron = new CronParser(cronDefinition).parse("*/2 * * * *");
    final ExecutionTime executionTime = ExecutionTime.forCron(cron);
    final ZonedDateTime time = ZonedDateTime.parse("2015-09-05T13:56:00.000-07:00");
    final Optional<ZonedDateTime> nextExecutionTime = executionTime.nextExecution(time);
    if (nextExecutionTime.isPresent()) {
        final ZonedDateTime next = nextExecutionTime.get();
        final Optional<ZonedDateTime> shouldBeInNextHourExecution = executionTime.nextExecution(next);
        if (shouldBeInNextHourExecution.isPresent()) {
            assertEquals(next.plusMinutes(2), shouldBeInNextHourExecution.get());
            return;
        }
    }
    fail("one of the asserted values was not present.");
}
 
Example #16
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #45: next execution does not match expected date. Result is not in same timezone as reference date.
 */
@Test
public void testMondayWeekdayNextExecution() {
    final String crontab = "* * * * 1";
    final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
    final CronParser parser = new CronParser(cronDefinition);
    final Cron cron = parser.parse(crontab);
    final ZonedDateTime date = ZonedDateTime.parse("2015-10-13T17:26:54.468-07:00");
    final ExecutionTime executionTime = ExecutionTime.forCron(cron);
    final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(date);
    if (nextExecution.isPresent()) {
        assertEquals(ZonedDateTime.parse("2015-10-19T00:00:00.000-07:00"), nextExecution.get());
    } else {
        fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #17
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #61: nextExecution over daylight savings is wrong.
 */
@Test
public void testNextExecutionDaylightSaving() {
    final CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX));
    final ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 17 * * *"));// daily at 17:00
    // Daylight savings for New York 2016 is Mar 13 at 2am
    final ZonedDateTime last = ZonedDateTime.of(2016, 3, 12, 17, 0, 0, 0, ZONE_ID_NEW_YORK);
    final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(last);
    if (nextExecution.isPresent()) {
        final long millis = Duration.between(last, nextExecution.get()).toMillis();
        assertEquals(23, (millis / 3600000));
        assertEquals(last.getZone(), nextExecution.get().getZone());
    } else {
        fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #18
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #61: lastExecution over daylight savings is wrong.
 */
@Test
public void testLastExecutionDaylightSaving() {
    final CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX));
    final ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 17 * * *"));// daily at 17:00
    // Daylight savings for New York 2016 is Mar 13 at 2am
    final ZonedDateTime now = ZonedDateTime.of(2016, 3, 12, 17, 0, 0, 0, ZoneId.of("America/Phoenix"));
    final Optional<ZonedDateTime> lastExecution = executionTime.lastExecution(now);
    if (lastExecution.isPresent()) {
        final long millis = Duration.between(lastExecution.get(), now).toMillis();
        assertEquals(24, (millis / 3600000));
        assertEquals(now.getZone(), lastExecution.get().getZone());
    } else {
        fail(LAST_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #19
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #79: Next execution skipping valid date.
 */
@Test
public void testNextExecution2014() {
    final String crontab = "0 8 * * 1";//m,h,dom,m,dow ; every monday at 8AM
    final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
    final CronParser parser = new CronParser(cronDefinition);
    final Cron cron = parser.parse(crontab);
    final ZonedDateTime date = ZonedDateTime.parse("2014-11-30T00:00:00Z");
    final ExecutionTime executionTime = ExecutionTime.forCron(cron);
    final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(date);
    if (nextExecution.isPresent()) {
        assertEquals(ZonedDateTime.parse("2014-12-01T08:00:00Z"), nextExecution.get());
    } else {
        fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
    }

}
 
Example #20
Source File: ExecutionTimeCustomDefinitionIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Test for issue #38
 * https://github.com/jmrozanec/cron-utils/issues/38
 * Reported case: lastExecution and nextExecution do not work properly
 * Expected: should return expected date
 */
@Test
public void testCronExpressionEveryTwoHoursAsteriskSlash() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.defineCron()
            .withSeconds().and()
            .withMinutes().and()
            .withHours().and()
            .withDayOfMonth().and()
            .withMonth().and()
            .withDayOfWeek().withValidRange(0, 7).withMondayDoWValue(1).withIntMapping(7, 0).and()
            .instance();

    final CronParser parser = new CronParser(cronDefinition);
    final Cron cron = parser.parse("0 0 */2 * * *");
    final ZonedDateTime startDateTime = ZonedDateTime.parse("2015-08-28T12:05:14.000-03:00");

    final Optional<ZonedDateTime> nextExecution = ExecutionTime.forCron(cron).nextExecution(startDateTime);
    if (nextExecution.isPresent()) {
        assertTrue(ZonedDateTime.parse("2015-08-28T14:00:00.000-03:00").compareTo(nextExecution.get()) == 0);
    } else {
        fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #21
Source File: Issue413Test.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testFridayToSaturdayUnix() {
    final CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX));
    try {
        parser.parse("* * * */12 *");
    } catch (IllegalArgumentException expected) {
        assertEquals("Failed to parse '* * * */12 *'. Period 12 not in range [1, 12]", expected.getMessage());
    }
}
 
Example #22
Source File: CronParserTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseMulticron(){
    String multicron = "0 0|0|30|0 9|10|11|12 * * ? *";
    parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
    Cron cron = parser.parse(multicron);
    assertEquals(multicron, cron.asString());
}
 
Example #23
Source File: OpenIssuesTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
private static ZonedDateTime nextSchedule(final String cronString, final ZonedDateTime lastExecution) {
    final CronParser cronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX));
    final Cron cron = cronParser.parse(cronString);

    final ExecutionTime executionTime = ExecutionTime.forCron(cron);

    final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(lastExecution);
    if (nextExecution.isPresent()) {
        return nextExecution.get();
    } else {
        throw new NullPointerException("next execution is not present");
    }
}
 
Example #24
Source File: Issue418Test.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidWeekDayEnd() {
    try {
        final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);
        final CronParser parser = new CronParser(cronDefinition);
        parser.parse("0 0 2 ? * 1/8 *");
        fail("Expected exception for invalid expression");
    } catch (IllegalArgumentException expected) {
        assertEquals("Failed to parse '0 0 2 ? * 1/8 *'. Period 8 not in range [1, 7]", expected.getMessage());
    }
}
 
Example #25
Source File: CronTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
public void testIssue308(){
    CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);
    CronParser parser = new CronParser(cronDefinition);
    Cron quartzCron = parser.parse("0 0 11 L-2 * ?");
    CronDescriptor descriptor = CronDescriptor.instance(Locale.ENGLISH);
    String description = descriptor.describe(quartzCron);

    // not sure what the exact string 'should' be ..
    assertEquals( "at 11:00 two days before the last day of month", description);
}
 
Example #26
Source File: CronParserTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Corresponds to issue#148
 * https://github.com/jmrozanec/cron-utils/issues/148
 */
@Test
public void testParseEveryXyears() {
    final CronDefinition quartzDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);
    parser = new CronParser(quartzDefinition);

    parser.parse("0/59 0/59 0/23 1/30 1/11 ? 2017/3");
}
 
Example #27
Source File: ExecutionTimeCustomDefinitionIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Test for issue #57
 * https://github.com/jmrozanec/cron-utils/issues/57
 * Reported case: BetweenDayOfWeekValueGenerator does not work for the first day of a month in some cases.
 * Expected: first day of month should be returned ok
 */
@Test
public void testCronExpressionBetweenDayOfWeekValueGeneratorCorrectFirstDayOfMonth() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.defineCron()
            .withMinutes().and()
            .withHours().and()
            .withDayOfMonth()
            .supportsL().supportsW()
            .and()
            .withMonth().and()
            .withDayOfWeek()
            .withMondayDoWValue(1)
            .withValidRange(1, 7)
            .supportsHash().supportsL()
            .and()
            .withYear().optional().and()
            .instance();

    final CronParser parser = new CronParser(cronDefinition);
    final Cron cron = parser.parse("30 3 * * MON-FRI");
    final ZonedDateTime sameDayBeforeEventStartDateTime = ZonedDateTime.parse("1970-01-01T00:00:00.000-03:00");
    final Optional<ZonedDateTime> sameDayBeforeEventStartDateTimeExecution = ExecutionTime.forCron(cron).nextExecution(sameDayBeforeEventStartDateTime);
    if (sameDayBeforeEventStartDateTimeExecution.isPresent()) {
        assertEquals(1, sameDayBeforeEventStartDateTimeExecution.get().getDayOfMonth());
    } else {
        fail("sameDayBeforeEventStartDateTimeExecution was not present");
    }

    final ZonedDateTime sameDayAfterEventStartDateTime = ZonedDateTime.parse("1970-01-01T12:00:00.000-03:00");
    final Optional<ZonedDateTime> sameDayAfterEventStartDateTimeExecution = ExecutionTime.forCron(cron).nextExecution(sameDayAfterEventStartDateTime);
    if (sameDayAfterEventStartDateTimeExecution.isPresent()) {
        assertEquals(2, sameDayAfterEventStartDateTimeExecution.get().getDayOfMonth());
    } else {
        fail("sameDayAfterEventStartDateTimeExecution was not present");
    }
}
 
Example #28
Source File: SimpleScheduler.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public SimpleScheduler(SchedulerContext context, Config config, SchedulerRuntimeConfig schedulerRuntimeConfig) {
    this.running = true;
    this.enabled = schedulerRuntimeConfig.enabled;
    this.scheduledTasks = new ArrayList<>();
    this.executor = context.getExecutor();

    if (!schedulerRuntimeConfig.enabled) {
        this.scheduledExecutor = null;
        LOGGER.info("Simple scheduler is disabled by config property and will not be started");
    } else if (context.getScheduledMethods().isEmpty()) {
        this.scheduledExecutor = null;
        LOGGER.info("No scheduled business methods found - Simple scheduler will not be started");
    } else {
        this.scheduledExecutor = new JBossScheduledThreadPoolExecutor(1, new Runnable() {
            @Override
            public void run() {
                // noop
            }
        });

        CronDefinition definition = CronDefinitionBuilder.instanceDefinitionFor(context.getCronType());
        CronParser parser = new CronParser(definition);

        for (ScheduledMethodMetadata method : context.getScheduledMethods()) {
            ScheduledInvoker invoker = context.createInvoker(method.getInvokerClassName());
            int nameSequence = 0;
            for (Scheduled scheduled : method.getSchedules()) {
                nameSequence++;
                SimpleTrigger trigger = createTrigger(method.getInvokerClassName(), parser, scheduled, nameSequence,
                        config);
                scheduledTasks.add(new ScheduledTask(trigger, invoker));
            }
        }
    }
}
 
Example #29
Source File: Issue55UnexpectedExecutionTimes.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Setup.
 */
@Before
public void setUp() {
    cronDefinition = CronDefinitionBuilder.defineCron()
            .withMinutes().and()
            .withHours().and()
            .withDayOfMonth()
            .supportsHash().supportsL().supportsW().supportsQuestionMark().and()
            .withMonth().and()
            .withDayOfWeek()//Monday=1
            .withIntMapping(7, 0) //we support non-standard non-zero-based numbers!
            .supportsHash().supportsL().supportsW().supportsQuestionMark().and()
            .withYear().optional().and()
            .withCronValidation(
                    //both a day-of-week AND a day-of-month parameter should fail for this case; otherwise returned values are correct
                    new CronConstraint("Both, a day-of-week AND a day-of-month parameter, are not supported.") {

                        private static final long serialVersionUID = -5934767434702909825L;

                        @Override
                        public boolean validate(final Cron cron) {
                            if (!(cron.retrieve(CronFieldName.DAY_OF_MONTH).getExpression() instanceof QuestionMark)) {
                                return cron.retrieve(CronFieldName.DAY_OF_WEEK).getExpression() instanceof QuestionMark;
                            } else {
                                return !(cron.retrieve(CronFieldName.DAY_OF_WEEK).getExpression() instanceof QuestionMark);
                            }
                        }
                    })
            .instance();
}
 
Example #30
Source File: Issue388Test.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
public void testLastAndNextExecutionWithDowAndDom() {

        ZonedDateTime dateTime = ZonedDateTime.of(2019, 07, 01, 8, 0, 0, 0, UTC);

        CronParser springCronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.SPRING));
        Cron springCron = springCronParser.parse("0 0 8 1-7 * SAT");
        ExecutionTime springExecutionTime = ExecutionTime.forCron(springCron);
        ZonedDateTime nextSpringExecutionTime = springExecutionTime.nextExecution(dateTime).get();
        ZonedDateTime lastSpringExecutionTime = springExecutionTime.lastExecution(dateTime).get();

        //quartz
        CronParser quartzCronParser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
        Cron quartzCron = quartzCronParser.parse("0 0 8 ? * SAT#1");
        ExecutionTime quartzExecutionTime = ExecutionTime.forCron(quartzCron);
        ZonedDateTime nextQuartzExecutionTime = quartzExecutionTime.nextExecution(dateTime).get();
        ZonedDateTime lastQuartzExecutionTime = quartzExecutionTime.lastExecution(dateTime).get();

        ZonedDateTime lastMonthFirstSaturday = dateTime.withMonth(6)
                                                       .with(firstInMonth(DayOfWeek.SATURDAY))
                                                       .withHour(8)
                                                       .withMinute(0)
                                                       .withSecond(0)
                                                       .withNano(0);
        ZonedDateTime nextMonthFirstSaturday = dateTime.withMonth(7)
                                                       .with(firstInMonth(DayOfWeek.SATURDAY))
                                                       .withHour(8)
                                                       .withMinute(0)
                                                       .withSecond(0)
                                                       .withNano(0);
        //quartz
        assertEquals(lastMonthFirstSaturday, lastQuartzExecutionTime);
        assertEquals(nextMonthFirstSaturday, nextQuartzExecutionTime);
        //spring
        assertEquals(lastMonthFirstSaturday, lastSpringExecutionTime);
        assertEquals(nextMonthFirstSaturday, nextSpringExecutionTime);

    }