Java源码示例:org.springframework.scheduling.support.CronSequenceGenerator
示例1
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);
}
}
示例2
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();
}
示例3
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() ) );
}
}
示例4
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;
}
}
示例5
@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"));
}
}
}
示例6
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);
}
}
示例7
@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());
}
}
示例8
public static Date getNextDateAfterNow(String cronExpression, Date now) {
CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cronExpression);
Date tmpDate = cronSequenceGenerator.next(now);
return tmpDate;
}
示例9
/**
* 得到 {@link CronSequenceGenerator}
*/
public CronSequenceGenerator toCron () {
return new CronSequenceGenerator( this.toCronString() );
}
示例10
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));
}
示例11
private LocalDateTime calculateNextStart(String schedule) {
Date next = new CronSequenceGenerator(schedule).next(new Date());
return LocalDateTime.ofInstant(next.toInstant(), ZoneId.systemDefault());
}
示例12
/**
* @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);
}