org.springframework.scheduling.support.CronSequenceGenerator Java Examples

The following examples show how to use org.springframework.scheduling.support.CronSequenceGenerator. 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: DeviceAlarmRule.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
public void validate() {
    if (type == null) {
        throw new IllegalArgumentException("类型不能为空");
    }

    if (type != MessageType.online && type != MessageType.offline && StringUtils.isEmpty(modelId)) {
        throw new IllegalArgumentException("属性/事件/功能ID不能为空");
    }

    if (trigger == TriggerType.timer) {
        if (StringUtils.isEmpty(cron)) {
            throw new IllegalArgumentException("cron表达式不能为空");
        }
        try {
            new CronSequenceGenerator(cron);
        } catch (Exception e) {
            throw new IllegalArgumentException("cron表达式格式错误", e);
        }
    }
    if (!CollectionUtils.isEmpty(filters)) {
        filters.forEach(ConditionFilter::validate);
    }
}
 
Example #2
Source File: Scheduling.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected long calculateNextCronDate(ScheduledTask task, long date, long currentDate, long frame) {
    CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(task.getCron(), getCurrentTimeZone());
    //if last start = 0 (task never has run) or to far in the past, we use (NOW - FRAME) timestamp for pivot time
    //this approach should work fine cause cron works with absolute time
    long pivotPreviousTime = Math.max(date, currentDate - frame);

    Date currentStart = null;
    Date nextDate = cronSequenceGenerator.next(new Date(pivotPreviousTime));
    while (nextDate.getTime() < currentDate) {//if next date is in past try to find next date nearest to now
        currentStart = nextDate;
        nextDate = cronSequenceGenerator.next(nextDate);
    }

    if (currentStart == null) {
        currentStart = nextDate;
    }
    log.trace("{}\n now={} frame={} currentStart={} lastStart={} cron={}",
            task, currentDate, frame, currentStart, task.getCron());
    return currentStart.getTime();
}
 
Example #3
Source File: JobConfigurationObjectBundleHook.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void validateJobConfigurationCronOrFixedDelay( List<ErrorReport> errorReports,
    JobConfiguration jobConfiguration )
{
    if ( jobConfiguration.getJobType().isCronSchedulingType() )
    {
        if ( jobConfiguration.getCronExpression() == null )
        {
            errorReports.add( new ErrorReport( JobConfiguration.class, ErrorCode.E7004, jobConfiguration.getUid() ) );
        }
        else if ( !CronSequenceGenerator.isValidExpression( jobConfiguration.getCronExpression() ) )
        {
            errorReports.add( new ErrorReport( JobConfiguration.class, ErrorCode.E7005 ) );
        }
    }

    if ( jobConfiguration.getJobType().isFixedDelaySchedulingType() && jobConfiguration.getDelay() == null )
    {
        errorReports.add( new ErrorReport( JobConfiguration.class, ErrorCode.E7007, jobConfiguration.getUid() ) );
    }
}
 
Example #4
Source File: DateService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public boolean isTrigger(TimeAlert alert, long monitorUpdateRate, ZonedDateTime currentTime) {
    try {
        String timeZone = alert.getTimeZone();
        CronSequenceGenerator cronExpression = getCronExpression(alert.getCron());
        ZonedDateTime zonedCurrentTime = dateTimeService.getZonedDateTime(currentTime.toInstant(), timeZone);
        LocalDateTime startTimeOfTheMonitorInterval = zonedCurrentTime.toLocalDateTime().minus(monitorUpdateRate, ChronoUnit.MILLIS);
        Date startDate = Date.from(startTimeOfTheMonitorInterval.toInstant(currentTime.getOffset()));
        Date nextTime = cronExpression.next(startDate);
        ZonedDateTime zonedNextTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(nextTime.getTime()), currentTime.getZone()).atZone(ZoneId.of(timeZone));
        long interval = (zonedCurrentTime.toEpochSecond() - zonedNextTime.toEpochSecond()) * TimeUtil.SECOND_TO_MILLISEC;

        boolean triggerReady = interval >= 0L && interval < monitorUpdateRate;
        if (triggerReady) {
            LOGGER.info("Time alert '{}' firing at '{}' compared to current time '{}' in timezone '{}'",
                    alert.getName(), zonedNextTime, zonedCurrentTime, timeZone);
        }
        return triggerReady;
    } catch (ParseException e) {
        LOGGER.error("Invalid cron expression '{}', cluster '{}'", e.getMessage(), alert.getCluster().getStackCrn());
        return false;
    }
}
 
Example #5
Source File: CronValidator.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(Object value) throws ValidationException {
    if (value != null) {
        ServerInfoService serverInfoService = AppBeans.get(ServerInfoService.NAME);
        Messages messages = AppBeans.get(Messages.NAME);
        try {
            new CronSequenceGenerator(value.toString(), serverInfoService.getTimeZone());
        } catch (Exception e) {
            throw new ValidationException(messages.getMessage(CronValidator.class, "validation.cronInvalid"));
        }
    }
}
 
Example #6
Source File: DateService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public CronSequenceGenerator getCronExpression(String cron) throws ParseException {
    String[] splits = cron.split("\\s+");
    if (splits.length < MINIMAL_CRON_SEGMENT_LENGTH && splits.length > MINIMAL_USER_DEFINED_CRON_SEGMENT_LENGTH) {
        for (int i = splits.length; i < MINIMAL_CRON_SEGMENT_LENGTH; i++) {
            cron = i == DAY_OF_WEEK_FIELD ? String.format("%s ?", cron) : String.format("%s *", cron);
        }
    }
    try {
        return new CronSequenceGenerator(cron);
    } catch (Exception ex) {
        throw new ParseException(ex.getMessage(), 0);
    }
}
 
Example #7
Source File: CronTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws ParseException {
    if (exception.isPresent()) {
        thrown.expect(exception.get());
    }
    CronSequenceGenerator cronExpression = underTest.getCronExpression(input);
    if (!exception.isPresent()) {
        Assert.assertEquals(String.format("CronSequenceGenerator: %s", expected.orElse("This should be null")), cronExpression.toString());
    }
}
 
Example #8
Source File: CronUtils.java    From chronus with Apache License 2.0 4 votes vote down vote up
public static Date getNextDateAfterNow(String cronExpression, Date now) {
    CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cronExpression);
    Date tmpDate = cronSequenceGenerator.next(now);
    return tmpDate;
}
 
Example #9
Source File: CustomizeCron.java    From spring-boot-start-current with Apache License 2.0 4 votes vote down vote up
/**
 * 得到 {@link CronSequenceGenerator}
 */
public CronSequenceGenerator toCron () {
	return new CronSequenceGenerator( this.toCronString() );
}
 
Example #10
Source File: ScheduledJobInstanceImpl.java    From haven-platform with Apache License 2.0 4 votes vote down vote up
private void checkCronAndSetStartDate(String schedule) {
    Assert.hasText(schedule, "parameters.schedule is empty or null");
    Assert.isTrue(CronSequenceGenerator.isValidExpression(schedule), "Cron expression is not valid: " + schedule);
    updateNextStart(calculateNextStart(schedule));
}
 
Example #11
Source File: ScheduledJobInstanceImpl.java    From haven-platform with Apache License 2.0 4 votes vote down vote up
private LocalDateTime calculateNextStart(String schedule) {
    Date next = new CronSequenceGenerator(schedule).next(new Date());
    return LocalDateTime.ofInstant(next.toInstant(), ZoneId.systemDefault());
}
 
Example #12
Source File: DefaultJobDefinition.java    From edison-microservice with Apache License 2.0 4 votes vote down vote up
/**
 * @param cron cron expression to validate.
 * @throws IllegalArgumentException if cron expression is invalid
 * @see CronSequenceGenerator
 */
public static void validateCron(String cron) {
    //Internally, we use the org.springframework.scheduling.support.CronTrigger which has a different syntax than the official crontab syntax.
    //Therefore we use the internal validation of CronTrigger
    new CronSequenceGenerator(cron);
}