com.cronutils.model.definition.CronDefinition Java Examples

The following examples show how to use com.cronutils.model.definition.CronDefinition. 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: Issue200Test.java    From cron-utils with Apache License 2.0 7 votes vote down vote up
@Test
public void testMustMatchCronEvenIfNanoSecondsVaries() {
    final CronDefinition cronDefinition =
            CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);

    final CronParser parser = new CronParser(cronDefinition);
    final Cron quartzCron = parser.parse("00 00 10 * * ?");

    quartzCron.validate();

    // NOTE: Off by 3 nano seconds
    final ZonedDateTime zdt = ZonedDateTime.of(1999, 07, 18, 10, 00, 00, 03, ZoneId.systemDefault());

    // Must be true
    assertTrue("Nano seconds must not affect matching of Cron Expressions", ExecutionTime.forCron(quartzCron).isMatch(zdt));
}
 
Example #3
Source File: SingleExecutionTime.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
SingleExecutionTime(final CronDefinition cronDefinition, final CronField yearsValueCronField, final CronField daysOfWeekCronField,
        final CronField daysOfMonthCronField, final CronField daysOfYearCronField, final TimeNode months, final TimeNode hours,
        final TimeNode minutes, final TimeNode seconds) {
    this.cronDefinition = Preconditions.checkNotNull(cronDefinition);
    FieldValueGenerator alwaysGenerator = FieldValueGeneratorFactory.forCronField(new CronField(CronFieldName.YEAR, Always.always(), FieldConstraintsBuilder.instance().createConstraintsInstance()));
    if(cronDefinition.containsFieldDefinition(CronFieldName.YEAR)){
        if(!cronDefinition.getFieldDefinition(CronFieldName.YEAR).isOptional()){
            Preconditions.checkNotNull(yearsValueCronField);
        }
        this.yearsValueGenerator = yearsValueCronField==null?alwaysGenerator:createYearValueGeneratorInstance(yearsValueCronField);
    } else{
        this.yearsValueGenerator = alwaysGenerator;
    }
    this.daysOfWeekCronField = Preconditions.checkNotNull(daysOfWeekCronField);
    this.daysOfMonthCronField = Preconditions.checkNotNull(daysOfMonthCronField);
    this.daysOfYearCronField = daysOfYearCronField;
    this.months = Preconditions.checkNotNull(months);
    this.hours = Preconditions.checkNotNull(hours);
    this.minutes = Preconditions.checkNotNull(minutes);
    this.seconds = Preconditions.checkNotNull(seconds);
}
 
Example #4
Source File: Issue293Test.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
@Test
   public void test() {
       CronDefinition def = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
       CronParser parser = new CronParser(def);

       Cron cron = parser.parse(cronText);
       ExecutionTime et = ExecutionTime.forCron(cron);

       ZonedDateTime vs = ZonedDateTime.of(2017, 12, 1, 9, 30, 0, 0, ZONE);
       assertEquals(DayOfWeek.FRIDAY, vs.getDayOfWeek());

       // Last match prior to our reference time
       ZonedDateTime expected = ZonedDateTime.of(2017, 11, 30, 18, 15, 0, 0, ZONE);
       assertEquals(DayOfWeek.THURSDAY, expected.getDayOfWeek());

Optional<ZonedDateTime> lastExecution = et.lastExecution(vs);
if (lastExecution.isPresent()) {
    ZonedDateTime actual = lastExecution.get();
    assertEquals(expected, actual);
} else {
    fail("last execution was not present");
}
   }
 
Example #5
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 #6
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 #7
Source File: Issue223Test.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #223: for dayOfWeek value == 3 && division of day, nextExecution do not return correct results.
 */
@Test
public void testEveryWednesdayOfEveryDayNextExecution() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
    final CronParser parser = new CronParser(cronDefinition);
    final Cron myCron = parser.parse("* * * * 3");
    ZonedDateTime time = ZonedDateTime.parse("2017-09-05T11:31:55.407-05:00");
    final Optional<ZonedDateTime> nextExecution = ExecutionTime.forCron(myCron).nextExecution(time);
    if (nextExecution.isPresent()) {
        assertEquals(ZonedDateTime.parse("2017-09-06T00:00-05:00"), nextExecution.get());
    } else {
        fail("next execution was not present");
    }

    final Cron myCron2 = parser.parse("* * */1 * 3");
    time = ZonedDateTime.parse("2017-09-05T11:31:55.407-05:00");
    final Optional<ZonedDateTime> nextExecution2 = ExecutionTime.forCron(myCron2).nextExecution(time);
    if (nextExecution2.isPresent()) {
        assertEquals(ZonedDateTime.parse("2017-09-06T00:00-05:00"), nextExecution2.get());
    } else {
        fail("next execution was not present");
    }
}
 
Example #8
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 #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: 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 #11
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 #12
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 #13
Source File: Issue340Test.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testDayOfWeekRollover() {
    // Every Friday to Tuesday (Fri, Sat, Sun, Mon, Tue) at 5 AM
    String schedule = "0 0 5 ? * FRI-TUE *";
    // Java DayOfWeek is MON (1) to SUN (7)
    Set<Integer> validDaysOfWeek = Sets.newSet(1, 2, 5, 6, 7);
    CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);
    CronParser parser = new CronParser(cronDefinition);
    Cron quartzCron = parser.parse(schedule);

    ZonedDateTime time = ZonedDateTime.now();
    ExecutionTime executionTime = ExecutionTime.forCron(quartzCron);

    // Check the next 100 execution times
    for (int i = 0; i < 100; i++) {
        Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(time);
        Assert.assertTrue(nextExecution.isPresent());
        time = nextExecution.get();
        int dayOfWeek = time.getDayOfWeek().getValue();
        Assert.assertTrue(validDaysOfWeek.contains(dayOfWeek));
        Assert.assertEquals(5, time.getHour());
        Assert.assertEquals(0, time.getMinute());
        Assert.assertEquals(0, time.getSecond());
    }
}
 
Example #14
Source File: CronParser.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Build possible cron expressions from definitions. One is built for sure. A second one may be build if last field is optional.
 *
 * @param cronDefinition - cron definition instance
 */
private void buildPossibleExpressions(final CronDefinition cronDefinition) {
    final List<CronParserField> sortedExpression = cronDefinition.getFieldDefinitions().stream()
            .map(this::toCronParserField)
            .sorted(CronParserField.createFieldTypeComparator())
            .collect(Collectors.toList());

    List<CronParserField> tempExpression = sortedExpression;

    while(lastFieldIsOptional(tempExpression)) {
        int expressionLength = tempExpression.size() - 1;
        ArrayList<CronParserField> possibleExpression = new ArrayList<>(tempExpression.subList(0, expressionLength));

        expressions.put(expressionLength, possibleExpression);
        tempExpression = possibleExpression;
    }

    expressions.put(sortedExpression.size(), sortedExpression);
}
 
Example #15
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 #16
Source File: CronValidator.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return true;
    }

    CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(type);
    CronParser cronParser = new CronParser(cronDefinition);
    try {
        cronParser.parse(value).validate();
        return true;
    } catch (IllegalArgumentException e) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(e.getMessage()).addConstraintViolation();
        return false;
    }
}
 
Example #17
Source File: Issue394Test.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testEveryMondayAt0900hours() {
    String cron = "0 0 9 * * MON";

    CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(SPRING);
    CronParser parser = new CronParser(cronDefinition);
    ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(cron));
    ZonedDateTime now = ZonedDateTime.now();
    Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(now);
    assertTrue(nextExecution.isPresent());
    // Should be the next Monday at 0900 hours
    assertEquals(DayOfWeek.MONDAY, nextExecution.get().getDayOfWeek());
    assertEquals(9, nextExecution.get().getHour());
    // The next execution after that should also be a Monday at 0900 hours, the following week
    ZonedDateTime nextExpectedExecution = nextExecution.get().plusWeeks(1);
    nextExecution = executionTime.nextExecution(nextExecution.get());
    assertTrue(nextExecution.isPresent());
    assertEquals(DayOfWeek.MONDAY, nextExecution.get().getDayOfWeek());
    assertEquals(9, nextExecution.get().getHour());
    assertEquals(nextExpectedExecution, nextExecution.get());
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
Source File: Issue406Test.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testDayOfWeekIsCorrectlyApplied() {
    // GIVEN a spring cron operating at 1AM every weekday
    final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.SPRING);
    final CronParser parser = new CronParser(cronDefinition);
    final ExecutionTime execTime = ExecutionTime.forCron(parser.parse("0 0 1 * * MON-FRI"));

    // WHEN I get the next execution at 3AM on Saturday
    final ZonedDateTime threeAmFifthJanuary2019 = ZonedDateTime.of(
        LocalDate.of(2019, 1, 5),
        LocalTime.of(3, 0),
        ZoneId.systemDefault()
    );
    final Optional<ZonedDateTime> nextExecution = execTime.nextExecution(threeAmFifthJanuary2019);
    
    // THEN the result is 1AM on Monday
    assertEquals(
        Optional.of(
                ZonedDateTime.of(
                LocalDate.of(2019, 1, 7),
                LocalTime.of(1, 0),
                ZoneId.systemDefault()
            )
        ),
        nextExecution
    );
}
 
Example #23
Source File: CompositeCronTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue263(){
    String multicron = "0 1 0 ? 1/1 MON#2|MON#3|MON#4|MON#5 *";
    CronDefinition definition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);
    CronParser parser = new CronParser(definition);
    Cron cron = parser.parse(multicron);
    assertEquals(multicron.replaceAll("MON", "2"), cron.asString());
}
 
Example #24
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 #25
Source File: ExecutionTimeCustomDefinitionIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testCronExpressionBeforeHalf() {

    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/30 * * * * *");

    final ZonedDateTime startDateTime = ZonedDateTime.of(2015, 8, 28, 12, 5, 14, 0, UTC);
    final ZonedDateTime expectedDateTime = ZonedDateTime.of(2015, 8, 28, 12, 5, 30, 0, UTC);

    final ExecutionTime executionTime = ExecutionTime.forCron(cron);

    final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(startDateTime);
    if (nextExecution.isPresent()) {
        assertEquals(expectedDateTime, nextExecution.get());
    } else {
        fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #26
Source File: ExecutionTimeCustomDefinitionIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testCronExpressionAfterHalf() {
    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("*/30 * * * * *");

    final ZonedDateTime startDateTime = ZonedDateTime.of(2015, 8, 28, 12, 5, 44, 0, UTC);
    final ZonedDateTime expectedDateTime = ZonedDateTime.of(2015, 8, 28, 12, 6, 0, 0, UTC);

    final ExecutionTime executionTime = ExecutionTime.forCron(cron);

    final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(startDateTime);
    if (nextExecution.isPresent()) {
        final ZonedDateTime nextExecutionDateTime = nextExecution.get();
        assertEquals(expectedDateTime, nextExecutionDateTime);
    } else {
        fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #27
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidDayInMonthCron() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
    final CronParser parser = new CronParser(cronDefinition);
    final Cron myCron = parser.parse("0 0 31 2 *");
    final ZonedDateTime time = ZonedDateTime.parse("2015-09-17T00:00:00.000-07:00");
    final Optional<ZonedDateTime> nextExecution = ExecutionTime.forCron(myCron).nextExecution(time);
    assertFalse(nextExecution.isPresent());
}
 
Example #28
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Issue #41: for everything other than a dayOfWeek value == 1, nextExecution and lastExecution do not return correct results.
 */
@Test
public void testEveryTuesdayAtThirdHourOfDayLastExecution() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
    final CronParser parser = new CronParser(cronDefinition);
    final Cron myCron = parser.parse("0 3 * * 3");
    final ZonedDateTime time = ZonedDateTime.parse("2015-09-17T00:00:00.000-07:00");
    final Optional<ZonedDateTime> lastExecution = ExecutionTime.forCron(myCron).lastExecution(time);
    if (lastExecution.isPresent()) {
        assertEquals(ZonedDateTime.parse("2015-09-16T03:00:00.000-07:00"), lastExecution.get());
    } else {
        fail(LAST_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #29
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Issue #41: for everything other than a dayOfWeek value == 1, nextExecution and lastExecution do not return correct results.
 */
@Test
public void testEveryTuesdayAtThirdHourOfDayNextExecution() {
    final CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX);
    final CronParser parser = new CronParser(cronDefinition);
    final Cron myCron = parser.parse("0 3 * * 3");
    final ZonedDateTime time = ZonedDateTime.parse("2015-09-17T00:00:00.000-07:00");
    final Optional<ZonedDateTime> nextExecution = ExecutionTime.forCron(myCron).nextExecution(time);
    if (nextExecution.isPresent()) {
        assertEquals(ZonedDateTime.parse("2015-09-23T03:00:00.000-07:00"), nextExecution.get());
    } else {
        fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example #30
Source File: TaskDescriptor.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Cron getCronTriggerTypeConfiguration(){
	if (TaskTriggerType.CRON.equals(getTriggerType())) {
		CronDefinition cronDefinition =
			CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);
		String cronExpression = getTriggerParameters().get("cron");
		if (cronExpression != null) {
			CronParser parser = new CronParser(cronDefinition);
			return parser.parse(cronExpression);
		}
		return CronBuilder.cron(cronDefinition).instance();
	}
	return null;
}