org.apache.logging.log4j.core.util.CronExpression Java Examples

The following examples show how to use org.apache.logging.log4j.core.util.CronExpression. 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: AlarmAdminService.java    From frostmourne with MIT License 6 votes vote down vote up
public boolean atomicSave(AlarmContract alarmContract) {
    boolean isValidCron = CronExpression.isValidExpression(alarmContract.getCron());
    if (!isValidCron) {
        throw new ProtocolException(510, "cron表达式非法");
    }
    padAlarm(alarmContract);
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = frostmourneTransactionManager.getTransaction(def);
    try {
        save(alarmContract);
    } catch (Exception ex) {
        frostmourneTransactionManager.rollback(status);
        LOGGER.error("error when save alarm", ex);
        throw ex;
    }
    frostmourneTransactionManager.commit(status);
    return true;
}
 
Example #2
Source File: CronTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testHoursRangeOnWeekend() throws ParseException {
    // every second, every minute, hour 14 to 15 on days of the week 1 and 7 --> from 14:00 to 15:59, on Saturday (7) and Sunday (1)
    CronExpression cronExpression = new CronExpression("* * 14-15 ? * 1,7");

    // Saturday November 24th, 2018
    Date d = Date.from(LocalDateTime.of(2018, 11, 24, 14, 00, 0).atZone(ZoneId.systemDefault()).toInstant());
    assertThat(cronExpression.isSatisfiedBy(d), is(true));
    // Sunday November 25th, 2018
    d = Date.from(LocalDateTime.of(2018, 11, 25, 14, 00, 0).atZone(ZoneId.systemDefault()).toInstant());
    assertThat(cronExpression.isSatisfiedBy(d), is(true));
    // the working day Monday to Friday, November 26th to November 30th, 2018
    for (int day = 26; day <= 30; day++) {
        d = Date.from(LocalDateTime.of(2018, 11, day, 14, 00, 0).atZone(ZoneId.systemDefault()).toInstant());
        assertThat(cronExpression.isSatisfiedBy(d), is(false));
    }
}
 
Example #3
Source File: CronTriggeringPolicy.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a ScheduledTriggeringPolicy.
 * 
 * @param configuration
 *            the Configuration.
 * @param evaluateOnStartup
 *            check if the file should be rolled over immediately.
 * @param schedule
 *            the cron expression.
 * @return a ScheduledTriggeringPolicy.
 */
@PluginFactory
public static CronTriggeringPolicy createPolicy(@PluginConfiguration final Configuration configuration,
        @PluginAttribute final String evaluateOnStartup,
        @PluginAttribute final String schedule) {
    CronExpression cronExpression;
    final boolean checkOnStartup = Boolean.parseBoolean(evaluateOnStartup);
    if (schedule == null) {
        LOGGER.info("No schedule specified, defaulting to Daily");
        cronExpression = getSchedule(defaultSchedule);
    } else {
        cronExpression = getSchedule(schedule);
        if (cronExpression == null) {
            LOGGER.error("Invalid expression specified. Defaulting to Daily");
            cronExpression = getSchedule(defaultSchedule);
        }
    }
    return new CronTriggeringPolicy(cronExpression, checkOnStartup, configuration);
}
 
Example #4
Source File: OfflineDataProcessingExecutor.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * Checks whether query is scheduled to run or not depending on runSchedule
 * and lastRunTime
 * 
 * @param runSchedule
 * @param lastRunTime
 * @return
 */
public Boolean isQueryScheduledToRun(Long runSchedule, String lastRunTime, String cronSchedule) {
	// if lastExecutionTime property is not added in the json file, we'll
	// execute the query by default
	if (lastRunTime == null && (cronSchedule == null || cronSchedule.trim().length() == 0)) {
		return Boolean.TRUE;
	}
	ZonedDateTime dateTime = null;
	ZonedDateTime now = ZonedDateTime.now(InsightsUtils.zoneId);
	Long timeDifferenceInMinutes = null;
	if (lastRunTime != null && !lastRunTime.isEmpty()) {
		dateTime = ZonedDateTime.parse(lastRunTime, formatter);
	}
	if(cronSchedule != null && cronSchedule.trim().length() > 0) {
		try {
			//"0 0 0 1 * ?"
			CronExpression convert = new CronExpressionConverter().convert(cronSchedule);
			if(dateTime == null) {
				dateTime = now.minusDays(1); //If the last run time not present, compare the cron time against last 24 hours.
			}
			Date cronDate = convert.getNextValidTimeAfter(Date.from(dateTime.toInstant()));
			if(cronDate.before(new Date())) {
				return Boolean.TRUE;
			}
		} catch (Exception e) {
			log.error("Unable to parse the CRON expression: "+cronSchedule, e);
		}
	}else {
		if (dateTime != null && now != null) {
			Duration d = Duration.between(dateTime, now);
			timeDifferenceInMinutes = d.abs().toMinutes();
		}
		if (timeDifferenceInMinutes > runSchedule) {
			return Boolean.TRUE;
		}
	}
	return Boolean.FALSE;
}
 
Example #5
Source File: CronTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testHoursRangeEveryDay() throws ParseException {
    // every second, every minute, hour 14 to 15 every day --> from 14:00 to 15:59
    CronExpression cronExpression = new CronExpression("* * 14-15 * * ?");

    Date d = Date.from(LocalDateTime.of(2018, 11, 26, 13, 59, 0).atZone(ZoneId.systemDefault()).toInstant());
    assertThat(cronExpression.isSatisfiedBy(d), is(false));
    d = Date.from(LocalDateTime.of(2018, 11, 26, 14, 00, 0).atZone(ZoneId.systemDefault()).toInstant());
    assertThat(cronExpression.isSatisfiedBy(d), is(true));
    d = Date.from(LocalDateTime.of(2018, 11, 26, 15, 59, 0).atZone(ZoneId.systemDefault()).toInstant());
    assertThat(cronExpression.isSatisfiedBy(d), is(true));
    d = Date.from(LocalDateTime.of(2018, 11, 26, 16, 00, 1).atZone(ZoneId.systemDefault()).toInstant());
    assertThat(cronExpression.isSatisfiedBy(d), is(false));
}
 
Example #6
Source File: CronTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testUserTimeZoneVsPodTimeZone() throws ParseException {
    // the "user" writes the cron expression in his timezone
    // every second, every minute, hour 14 to 15 every day --> from 14:00 to 15:59
    CronExpression cronExpression = new CronExpression("* * 14-15 * * ?");

    // the pod is running on a "Pacific/Easter" timezone data center, so cron expression needs the right timezone for evaluation
    cronExpression.setTimeZone(TimeZone.getTimeZone(ZoneId.of("Europe/Rome")));

    // it's really 08:00 in "Pacific/Easter" but 14:00 for "user"
    Date d = Date.from(LocalDateTime.of(2018, 11, 26, 8, 00, 0).atZone(ZoneId.of("Pacific/Easter")).toInstant());
    assertThat(cronExpression.isSatisfiedBy(d), is(true));
}
 
Example #7
Source File: CronTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testUtcTimeZone() throws ParseException {
    // the "user" writes the cron expression in UTC timezone, but let's imagine he is in Europe/Rome timezone
    // every second, every minute, hour 15 to 16 every day --> from 15:00 to 15:59
    CronExpression cronExpression = new CronExpression("* * 14-15 * * ?");

    // the pod is running on a "Pacific/Easter" timezone data center, so cron expression needs the right timezone for evaluation
    cronExpression.setTimeZone(TimeZone.getTimeZone("GMT"));

    // it's really 09:00 in "Pacific/Easter" but 15:00 for "user" so 14:00 in UTC
    Date d = Date.from(LocalDateTime.of(2018, 11, 26, 9, 00, 0).atZone(ZoneId.of("Pacific/Easter")).toInstant());
    assertThat(cronExpression.isSatisfiedBy(d), is(true));
}
 
Example #8
Source File: ConfigurationScheduler.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and executes an action that first based on a cron expression.
 * @param cronExpression the cron expression describing the schedule.
 * @param startDate The time to use as the time to begin the cron expression. Defaults to the current date and time.
 * @param command The Runnable to run,
 * @return a ScheduledFuture representing the next time the command will run.
 */
public CronScheduledFuture<?> scheduleWithCron(final CronExpression cronExpression, final Date startDate, final Runnable command) {
    final Date fireDate = cronExpression.getNextValidTimeAfter(startDate == null ? new Date() : startDate);
    final CronRunnable runnable = new CronRunnable(command, cronExpression);
    final ScheduledFuture<?> future = schedule(runnable, nextFireInterval(fireDate), TimeUnit.MILLISECONDS);
    final CronScheduledFuture<?> cronScheduledFuture = new CronScheduledFuture<>(future, fireDate);
    runnable.setScheduledFuture(cronScheduledFuture);
    LOGGER.debug("{} scheduled cron expression {} to fire at {}", name, cronExpression.getCronExpression(), fireDate);
    return cronScheduledFuture;
}
 
Example #9
Source File: CronTriggeringPolicy.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static CronExpression getSchedule(final String expression) {
    try {
        return new CronExpression(expression);
    } catch (final ParseException pe) {
        LOGGER.error("Invalid cron expression - " + expression, pe);
        return null;
    }
}
 
Example #10
Source File: ConfigurationScheduler.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public CronRunnable(final Runnable runnable, final CronExpression cronExpression) {
    this.cronExpression = cronExpression;
    this.runnable = runnable;
}
 
Example #11
Source File: CoreTypeConverters.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public CronExpression convert(final String s) throws Exception {
    return new CronExpression(s);
}
 
Example #12
Source File: CronTriggeringPolicy.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private CronTriggeringPolicy(final CronExpression schedule, final boolean checkOnStartup,
        final Configuration configuration) {
    this.cronExpression = Objects.requireNonNull(schedule, "schedule");
    this.configuration = Objects.requireNonNull(configuration, "configuration");
    this.checkOnStartup = checkOnStartup;
}
 
Example #13
Source File: CronTriggeringPolicy.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public CronExpression getCronExpression() {
    return cronExpression;
}
 
Example #14
Source File: RollingAppenderCronOnceADayTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testAppender() throws Exception {
    // TODO Is there a better way to test than putting the thread to sleep all over the place?
    final Logger logger = loggerContextRule.getLogger();
    final File file = new File(FILE);
    assertTrue("Log file does not exist", file.exists());
    logger.debug("This is test message number 1, waiting for rolling");

    final RollingFileAppender app = (RollingFileAppender) loggerContextRule.getLoggerContext().getConfiguration().getAppender("RollingFile");
    final TriggeringPolicy policy = app.getManager().getTriggeringPolicy();
    assertNotNull("No triggering policy", policy);
    assertTrue("Incorrect policy type", policy instanceof CronTriggeringPolicy);
    final CronExpression expression = ((CronTriggeringPolicy) policy).getCronExpression();
    assertEquals("Incorrect cron expresion", cronExpression, expression.getCronExpression());
    logger.debug("Cron expression will be {}", expression.getCronExpression());

    // force a reconfiguration
    for (int i = 1; i <= 20; ++i) {
        logger.debug("Adding first event {}", i);
    }

    Thread.sleep(remainingTime);
    final File dir = new File(DIR);
    assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0);

    for (int i = 1; i < 5; i++) {
      logger.debug("Adding some more event {}", i);
      Thread.sleep(1000);
    }
    final Matcher<File> hasGzippedFile = hasName(that(endsWith(".gz")));
    int count = 0;
    final File[] files = dir.listFiles();
    for (final File generatedFile : files) {
      if (hasGzippedFile.matches(generatedFile)) {
          count++;
      }
    }

    assertNotEquals("No compressed files found", 0, count);
    assertEquals("Multiple files found" , 1, count);
}
 
Example #15
Source File: ConfigurationScheduler.java    From logging-log4j2 with Apache License 2.0 2 votes vote down vote up
/**
 * Creates and executes an action that first based on a cron expression.
 * @param cronExpression the cron expression describing the schedule.
 * @param command The Runnable to run,
 * @return a ScheduledFuture representing the next time the command will run.
 */
public CronScheduledFuture<?> scheduleWithCron(final CronExpression cronExpression, final Runnable command) {
    return scheduleWithCron(cronExpression, new Date(), command);
}