Java Code Examples for com.cronutils.model.time.ExecutionTime#forCron()

The following examples show how to use com.cronutils.model.time.ExecutionTime#forCron() . 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: 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 3
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 4
Source File: TimeUtil.java    From styx with Apache License 2.0 5 votes vote down vote up
public static Instant previousInstant(Instant instant, Schedule schedule) {
  final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule));
  final ZonedDateTime utcDateTime = instant.atZone(UTC);

  return executionTime.lastExecution(utcDateTime)
      .orElseThrow(IllegalArgumentException::new) // with unix cron, this should not happen
      .toInstant();
}
 
Example 5
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 6
Source File: CronParserQuartzIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Issue #78: ExecutionTime.forCron fails on intervals
 */
@Test
public void testIntervalSeconds() {
    final ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0/20 * * * * ?"));
    final ZonedDateTime now = ZonedDateTime.parse("2005-08-09T18:32:42Z");
    final Optional<ZonedDateTime> lastExecution = executionTime.lastExecution(now);
    if (lastExecution.isPresent()) {
        final ZonedDateTime assertDate = ZonedDateTime.parse("2005-08-09T18:32:40Z");
        assertEquals(assertDate, lastExecution.get());
    } else {
        fail(LAST_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example 7
Source File: Issue143Test.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testCase2() {
    final ExecutionTime et = ExecutionTime.forCron(parser.parse("0 0 12 ? 12 SAT#5 *"));
    final Optional<ZonedDateTime> lastExecution = et.lastExecution(currentDateTime);
    if (lastExecution.isPresent()) {
        final ZonedDateTime expected = ZonedDateTime.of(LocalDateTime.of(2012, 12, 29, 12, 0), ZoneId.systemDefault());
        Assert.assertEquals(expected, lastExecution.get());
    } else {
        fail(LAST_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example 8
Source File: CronParserQuartzIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Issue #78: ExecutionTime.forCron fails on intervals
 */
@Test
public void testIntervalMinutes() {
    final ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("0 0/7 * * * ?"));
    final ZonedDateTime now = ZonedDateTime.parse("2005-08-09T18:32:42Z");
    final Optional<ZonedDateTime> lastExecution = executionTime.lastExecution(now);
    if (lastExecution.isPresent()) {
        final ZonedDateTime assertDate = ZonedDateTime.parse("2005-08-09T18:28:00Z");
        assertEquals(assertDate, lastExecution.get());
    } else {
        fail(LAST_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example 9
Source File: Issue143Test.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testCase4() {
    final ExecutionTime et = ExecutionTime.forCron(parser.parse("0 0 12 ? 1/1 SAT#5 *"));
    final Optional<ZonedDateTime> lastExecution = et.lastExecution(currentDateTime);
    if (lastExecution.isPresent()) {
        final ZonedDateTime expected = ZonedDateTime.of(LocalDateTime.of(2016, 10, 29, 12, 0), ZoneId.systemDefault());
        Assert.assertEquals(expected, lastExecution.get());
    } else {
        fail(LAST_EXECUTION_NOT_PRESENT_ERROR);
    }
}
 
Example 10
Source File: TimerTaskExecutorProvider.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
private Supplier<Duration> createNextDelay() {
    ValueObject config = ValueObject.of(context.getJob().getConfiguration());

    CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
    Cron cron = config.getString("cron")
        .map(parser::parse)
        .orElseThrow(() -> new IllegalArgumentException("cron配置不存在"));
    ExecutionTime executionTime = ExecutionTime.forCron(cron);

    return () -> executionTime.timeToNextExecution(ZonedDateTime.now()).orElse(Duration.ofSeconds(10));

}
 
Example 11
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);

    }
 
Example 12
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsMatchForUnix01() {
    final CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX));
    final String crontab = "* * * * *";//m,h,dom,M,dow
    final Cron cron = parser.parse(crontab);
    final ExecutionTime executionTime = ExecutionTime.forCron(cron);
    final ZonedDateTime scanTime = ZonedDateTime.parse("2016-02-29T11:00:00.000-06:00");
    assertTrue(executionTime.isMatch(scanTime));
}
 
Example 13
Source File: Issue423Test.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
    public void issue423() {
        final CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
        final Cron cron = parser.parse("0 0 0-07,17-0 ? * SAT");
        final CronDescriptor cd = CronDescriptor.instance(Locale.UK);
        assertTrue(cd.describe(cron).length() > 0);
        // at time of test creation, the descriptor is
        // "every hour between 0 and 7 and every hour between 17 and 0 at Saturday day"

        final ExecutionTime et = ExecutionTime.forCron(cron);
        // At this point, an an exception WAS logged. But, not anymore!

        Arrays.asList(
            new TestPair(shortZDT( 0,  0), shortZDT( 1, 0)),
            new TestPair(shortZDT( 0, 30), shortZDT( 1, 0)),
            new TestPair(shortZDT( 6,  0), shortZDT( 7, 0)),
            new TestPair(shortZDT( 7,  0), shortZDT(17, 0)),
            new TestPair(shortZDT(16,  0), shortZDT(17, 0)), // Should be 17:00, but skips to the next Saturday
            new TestPair(shortZDT(17,  0), shortZDT(18, 0)), // Should be 18:00, but skips to the next Saturday
            new TestPair(shortZDT(18,  0), shortZDT(19, 0))  // Should be 19:00, but skips to the next Saturday
        ).forEach(tp -> {
//            System.err.println("Expected: " + tp.expected + "; Actual: " + et.nextExecution(tp.test).get().toString());
            assertEquals(
                "All these should be on the same Saturday",
                tp.expected,
                et.nextExecution(tp.test).get()
            );
        });
    }
 
Example 14
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsMatchForUnix02() {
    final CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX));
    final String crontab = "0 * * * 1-5";//m,h,dom,M,dow
    final Cron cron = parser.parse(crontab);
    final ExecutionTime executionTime = ExecutionTime.forCron(cron);
    final ZonedDateTime scanTime = ZonedDateTime.parse("2016-03-04T11:00:00.000-06:00");
    assertTrue(executionTime.isMatch(scanTime));
}
 
Example 15
Source File: Issue332Test.java    From cron-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsMatchDailightSavingsChange_loop() {
    CronParser cronparser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX));
    ZonedDateTime date = ZonedDateTime.of(2018, 8, 12, 3, 0, 0, 0, ZoneId.of("America/Santiago"));
    Cron cron = cronparser.parse("0 6 * * *");
    ExecutionTime exectime = ExecutionTime.forCron(cron);
    exectime.isMatch(date);
}
 
Example 16
Source File: Issue404Test.java    From cron-utils with Apache License 2.0 4 votes vote down vote up
@Ignore
@Test
public void testNovember3Noon() {
	final CronDefinition cronDefinition = CronDefinitionBuilder.defineCron().withMinutes().and().withHours().and()
		.withDayOfWeek().and().instance();

	final Cron cron = new CronParser(cronDefinition).parse("0 0 *");

	final ExecutionTime executionTime = ExecutionTime.forCron(cron);

	final ZonedDateTime time = LocalDateTime.of(2019, 11, 3, 12, 0, 0).atZone(ZoneId.of("America/Sao_Paulo"));

	final Duration timeFromLastExecution = executionTime.timeFromLastExecution(time).get();

	Assert.assertEquals(12, timeFromLastExecution.toHours());
}
 
Example 17
Source File: ExecutionTimeUnixIntegrationTest.java    From cron-utils with Apache License 2.0 4 votes vote down vote up
/**
 * Issue #112: Calling nextExecution on a date-time during the overlap hour of DST causes an incorrect offset
 * to be returned.
 */
@Test
public void testDSTOverlap() {
    final ZoneId zoneId = ZONE_ID_NEW_YORK;

    // For the America/New_York time zone, DST ends (UTC-4:00 to UTC-5:00 / EDT -> EST) at 2:00 AM
    // on the these days for the years 2015-2026:
    final Set<LocalDate> dstDates = new HashSet<>();
    dstDates.add(LocalDate.of(2015, Month.NOVEMBER, 1));
    dstDates.add(LocalDate.of(2016, Month.NOVEMBER, 6));
    dstDates.add(LocalDate.of(2017, Month.NOVEMBER, 5));
    dstDates.add(LocalDate.of(2018, Month.NOVEMBER, 4));
    dstDates.add(LocalDate.of(2019, Month.NOVEMBER, 3));
    dstDates.add(LocalDate.of(2020, Month.NOVEMBER, 1));
    dstDates.add(LocalDate.of(2021, Month.NOVEMBER, 7));
    dstDates.add(LocalDate.of(2022, Month.NOVEMBER, 6));
    dstDates.add(LocalDate.of(2023, Month.NOVEMBER, 5));
    dstDates.add(LocalDate.of(2024, Month.NOVEMBER, 3));
    dstDates.add(LocalDate.of(2025, Month.NOVEMBER, 2));
    dstDates.add(LocalDate.of(2026, Month.NOVEMBER, 1));

    // Starting at 12 AM Nov. 1, 2015
    ZonedDateTime date = ZonedDateTime.of(2015, 11, 1, 0, 0, 0, 0, zoneId);

    final CronParser parser = new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX));
    // Scheduling pattern for 1:30 AM for the first 7 days of every November
    final ExecutionTime executionTime = ExecutionTime.forCron(parser.parse("30 1 1-7 11 *"));

    final ZoneOffset easternDaylightTimeOffset = ZoneOffset.ofHours(-4);
    final ZoneOffset easternStandardTimeOffset = ZoneOffset.ofHours(-5);

    for (int year = 2015; year <= 2026; year++) {
        boolean pastDSTEnd = false;
        int dayOfMonth = 1;
        while (dayOfMonth < 8) {
            final LocalDateTime expectedLocalDateTime = LocalDateTime.of(year, Month.NOVEMBER, dayOfMonth, 1, 30);
            final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(date);
            assert (nextExecution.isPresent());
            date = nextExecution.get();

            final ZoneOffset expectedOffset = pastDSTEnd ? easternStandardTimeOffset : easternDaylightTimeOffset;

            if (dstDates.contains(LocalDate.of(year, Month.NOVEMBER, dayOfMonth))) {
                if (!pastDSTEnd) {
                    // next iteration should be past the DST transition
                    pastDSTEnd = true;
                } else {
                    dayOfMonth++;
                }
            } else {
                dayOfMonth++;
            }
            assertEquals(ZonedDateTime.ofInstant(expectedLocalDateTime, expectedOffset, zoneId), date);
        }
    }
}
 
Example 18
Source File: CronSchedule.java    From Wisp with Apache License 2.0 4 votes vote down vote up
public CronSchedule(Cron cronExpression, ZoneId zoneId) {
	this.cronExpression = ExecutionTime.forCron(cronExpression);
	this.description = ENGLISH_DESCRIPTOR.describe(cronExpression);
	this.zoneId = zoneId;
}
 
Example 19
Source File: MaintenanceScheduleHelper.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Calculate the next available maintenance window.
 *
 * @param cronSchedule
 *            is a cron expression with 6 mandatory fields and 1 last
 *            optional field: "second minute hour dayofmonth month weekday
 *            year".
 * @param duration
 *            in HH:mm:ss format specifying the duration of a maintenance
 *            window, for example 00:30:00 for 30 minutes.
 * @param timezone
 *            is the time zone specified as +/-hh:mm offset from UTC. For
 *            example +02:00 for CET summer time and +00:00 for UTC. The
 *            start time of a maintenance window calculated based on the
 *            cron expression is relative to this time zone.
 *
 * @return { @link Optional<ZonedDateTime>} of the next available window. In
 *         case there is none, or there are maintenance window validation
 *         errors, returns empty value.
 * 
 */
// Exception squid:S1166 - if there are validation error(format of cron
// expression or duration is wrong), we simply return empty value
@SuppressWarnings("squid:S1166")
public static Optional<ZonedDateTime> getNextMaintenanceWindow(final String cronSchedule, final String duration,
        final String timezone) {
    try {
        final ExecutionTime scheduleExecutor = ExecutionTime.forCron(getCronFromExpression(cronSchedule));
        final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.of(timezone));
        final ZonedDateTime after = now.minus(convertToISODuration(duration));
        final ZonedDateTime next = scheduleExecutor.nextExecution(after);
        return Optional.of(next);
    } catch (final RuntimeException ignored) {
        return Optional.empty();
    }
}
 
Example 20
Source File: Issue404Test.java    From cron-utils with Apache License 2.0 3 votes vote down vote up
@Test
public void testSaturdayMidnight() {
	final CronDefinition cronDefinition = CronDefinitionBuilder.defineCron().withMinutes().and().withHours().and()
		.withDayOfWeek().and().instance();

	final Cron cron = new CronParser(cronDefinition).parse("0 0 *");

	final ExecutionTime executionTime = ExecutionTime.forCron(cron);

	final ZonedDateTime time = LocalDateTime.of(2019, 11, 2, 0, 0, 1).atZone(ZoneId.of("America/Sao_Paulo"));

	final Duration timeFromLastExecution = executionTime.timeFromLastExecution(time).get();

	Assert.assertEquals(1, timeFromLastExecution.getSeconds());
}