本文整理汇总了Java中com.cronutils.model.Cron类的典型用法代码示例。如果您正苦于以下问题:Java Cron类的具体用法?Java Cron怎么用?Java Cron使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Cron类属于com.cronutils.model包,在下文中一共展示了Cron类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: newMirror
import com.cronutils.model.Cron; //导入依赖的package包/类
private static <T extends Mirror> T newMirror(String remoteUri, Class<T> mirrorType) {
final MirrorCredential credential = mock(MirrorCredential.class);
final Repository localRepo = mock(Repository.class);
final Mirror mirror = Mirror.of(mock(Cron.class), MirrorDirection.LOCAL_TO_REMOTE,
credential, localRepo, "/", URI.create(remoteUri));
assertThat(mirror).isInstanceOf(mirrorType);
assertThat(mirror.direction()).isEqualTo(MirrorDirection.LOCAL_TO_REMOTE);
assertThat(mirror.credential()).isSameAs(credential);
assertThat(mirror.localRepo()).isSameAs(localRepo);
assertThat(mirror.localPath()).isEqualTo("/");
@SuppressWarnings("unchecked")
final T castMirror = (T) mirror;
return castMirror;
}
示例2: parse
import com.cronutils.model.Cron; //导入依赖的package包/类
/**
* Parse string with cron expression.
*
* @param expression - cron expression, never null
* @return Cron instance, corresponding to cron expression received
* @throws java.lang.IllegalArgumentException if expression does not match cron definition
*/
public Cron parse(final String expression) {
Preconditions.checkNotNull(expression, "Expression must not be null");
final String replaced = expression.replaceAll("\\s+", " ").trim();
if (StringUtils.isEmpty(replaced)) {
throw new IllegalArgumentException("Empty expression!");
}
final String[] expressionParts = replaced.toUpperCase().split(" ");
final int expressionLength = expressionParts.length;
final List<CronParserField> fields = expressions.get(expressionLength);
if (fields == null) {
throw new IllegalArgumentException(
String.format("Cron expression contains %s parts but we expect one of %s", expressionLength, expressions.keySet()));
}
try {
final int size = fields.size();
final List<CronField> results = new ArrayList<>(size + 1);
for (int j = 0; j < size; j++) {
results.add(fields.get(j).parse(expressionParts[j]));
}
return new Cron(cronDefinition, results).validate();
} catch (final IllegalArgumentException e) {
throw new IllegalArgumentException(String.format("Failed to parse '%s'. %s", expression, e.getMessage()), e);
}
}
示例3: ensureEitherDayOfWeekOrDayOfMonth
import com.cronutils.model.Cron; //导入依赖的package包/类
public static CronConstraint ensureEitherDayOfWeekOrDayOfMonth() {
//Solves issue #63: https://github.com/jmrozanec/cron-utils/issues/63
//both a day-of-week AND a day-of-month parameter should fail for QUARTZ
return new CronConstraint("Both, a day-of-week AND a day-of-month parameter, are not supported.") {
private static final long serialVersionUID = -4423693913868081656L;
@Override
public boolean validate(Cron cron) {
CronField dayOfYearField = cron.retrieve(CronFieldName.DAY_OF_YEAR);
if (dayOfYearField == null || dayOfYearField.getExpression() instanceof QuestionMark) {
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);
}
}
return true;
}
};
}
示例4: testCronExpressionEveryTwoHoursAsteriskSlash
import com.cronutils.model.Cron; //导入依赖的package包/类
/**
* 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);
}
}
示例5: setQuestionMark
import com.cronutils.model.Cron; //导入依赖的package包/类
private static Function<Cron, Cron> setQuestionMark() {
return cron -> {
final CronField dow = cron.retrieve(CronFieldName.DAY_OF_WEEK);
final CronField dom = cron.retrieve(CronFieldName.DAY_OF_MONTH);
if (dow == null && dom == null) {
return cron;
}
if (dow.getExpression() instanceof QuestionMark || dom.getExpression() instanceof QuestionMark) {
return cron;
}
final Map<CronFieldName, CronField> fields = new EnumMap<>(CronFieldName.class);
fields.putAll(cron.retrieveFieldsAsMap());
if (dow.getExpression() instanceof Always) {
fields.put(CronFieldName.DAY_OF_WEEK,
new CronField(CronFieldName.DAY_OF_WEEK, questionMark(), fields.get(CronFieldName.DAY_OF_WEEK).getConstraints()));
} else {
if (dom.getExpression() instanceof Always) {
fields.put(CronFieldName.DAY_OF_MONTH,
new CronField(CronFieldName.DAY_OF_MONTH, questionMark(), fields.get(CronFieldName.DAY_OF_MONTH).getConstraints()));
} else {
cron.validate();
}
}
return new Cron(cron.getCronDefinition(), new ArrayList<>(fields.values()));
};
}
示例6: testCronWithFirstWorkDayOfWeek
import com.cronutils.model.Cron; //导入依赖的package包/类
/**
* Issue #75: W flag not behaving as expected: did not return first workday of month, but an exception.
*/
@Test
public void testCronWithFirstWorkDayOfWeek() {
final String cronText = "0 0 12 1W * ? *";
final Cron cron = parser.parse(cronText);
final ZonedDateTime dt = ZonedDateTime.parse("2016-03-29T00:00:59Z");
final ExecutionTime executionTime = ExecutionTime.forCron(cron);
final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(dt);
if (nextExecution.isPresent()) {
final ZonedDateTime nextRun = nextExecution.get();
assertEquals("incorrect Day", nextRun.getDayOfMonth(), 1); // should be April 1st (Friday)
} else {
fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
}
}
示例7: testMustMatchCronEvenIfNanoSecondsVaries
import com.cronutils.model.Cron; //导入依赖的package包/类
@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));
}
示例8: testDescribeEveryXTimeUnits
import com.cronutils.model.Cron; //导入依赖的package包/类
@Test
public void testDescribeEveryXTimeUnits() {
final int time = 3;
final Every expression = new Every(new IntegerFieldValue(time));
assertEquals(String.format("every %s seconds", time), descriptor.describe(
new Cron(mockDefinition, Collections.singletonList(new CronField(CronFieldName.SECOND, expression, nullFieldConstraints)))
)
);
assertEquals(String.format("every %s minutes", time), descriptor.describe(
new Cron(mockDefinition, Collections.singletonList(new CronField(CronFieldName.MINUTE, expression, nullFieldConstraints)))
)
);
final List<CronField> params = new ArrayList<>();
params.add(new CronField(CronFieldName.HOUR, expression, nullFieldConstraints));
params.add(new CronField(CronFieldName.MINUTE, new On(new IntegerFieldValue(time)), nullFieldConstraints));
assertEquals(String.format("every %s hours at minute %s", time, time), descriptor.describe(new Cron(mockDefinition, params)));
}
示例9: testNextExecution2014
import com.cronutils.model.Cron; //导入依赖的package包/类
/**
* 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);
}
}
示例10: testCronExpressionEveryTwoHoursSlash
import com.cronutils.model.Cron; //导入依赖的package包/类
/**
* 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);
}
}
示例11: lastDayOfTheWeek
import com.cronutils.model.Cron; //导入依赖的package包/类
/**
* 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);
}
}
示例12: checkCron
import com.cronutils.model.Cron; //导入依赖的package包/类
private boolean checkCron(String cronExpression, ZonedDateTime now) {
try {
if (cronExpression == null || cronExpression.isEmpty()) {
return false;
}
Cron cron = parseCron(cronExpression);
ExecutionTime executionTime = ExecutionTime.forCron(cron);
ZonedDateTime last = executionTime.lastExecution(now);
boolean b1 = last.isAfter(prevChecked);
boolean b2 = last.isBefore(now);
LOGGER.info("cron={} now={} last={} prevCheck={} b1={} b2={}", cronExpression, now.toString(), last.toString(), prevChecked.toString(), b1, b2);
return (b1 && b2);
//return (last.isAfter(lastChecked) && last.isBefore(now));
} catch (Exception e) {
LOGGER.error("Check cron '{}' failed, {}", cronExpression, e.getMessage());
return false;
}
}
示例13: testNextExecutionTimeProperlySet
import com.cronutils.model.Cron; //导入依赖的package包/类
/**
* 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);
}
}
示例14: testEveryTwoMinRollsOverHour
import com.cronutils.model.Cron; //导入依赖的package包/类
/**
* 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.");
}
示例15: testMatchWorksAsExpectedForCustomCronsWhenPreviousOrNextOccurrenceIsMissing
import com.cronutils.model.Cron; //导入依赖的package包/类
/**
* 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);
}
}