
com.atlassian.bamboo.specs.api.util.CronExpressionCreationHelper Maven / Gradle / Ivy
package com.atlassian.bamboo.specs.api.util;
import com.atlassian.bamboo.specs.api.exceptions.PropertiesValidationException;
import org.jetbrains.annotations.NotNull;
import java.time.DayOfWeek;
import java.time.LocalTime;
import java.time.temporal.TemporalField;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.atlassian.bamboo.specs.api.validators.common.ImporterUtils.checkNotNull;
import static com.atlassian.bamboo.specs.api.validators.common.ImporterUtils.checkPositive;
public final class CronExpressionCreationHelper {
private CronExpressionCreationHelper() {
}
public static String scheduleEvery(int every, @NotNull TimeUnit at) {
checkNotNull("at", at);
checkPositive("every", every);
switch (at) {
case SECONDS:
return String.format("0/%d * * ? * *", every);
case MINUTES:
return String.format("0 0/%d * ? * *", every);
case HOURS:
return String.format("0 0 0/%d ? * *", every);
default:
throw new PropertiesValidationException(String.format("Don't know how to schedule: %s. Please use other methods or define cron expression manually", at));
}
}
public static String scheduleOnceDaily(@NotNull LocalTime at) {
checkNotNull("at", at);
return String.format("0 %d %d ? * *", at.getMinute(), at.getHour());
}
public static String scheduleWeekly(@NotNull LocalTime at, @NotNull DayOfWeek... onDays) {
checkNotNull("at", at);
checkNotNull("on", onDays);
List daysOfWeek = new ArrayList<>();
Collections.addAll(daysOfWeek, onDays);
return scheduleWeekly(at, daysOfWeek);
}
public static String scheduleWeekly(@NotNull LocalTime at, @NotNull Collection days) {
checkNotNull("at", at);
checkNotNull("days", days);
StringBuilder daysExpression = new StringBuilder();
Iterator iterator = days.iterator();
if (iterator.hasNext()) {
daysExpression.append(getCronDayOfWeekValue(iterator.next()));
while (iterator.hasNext()) {
daysExpression.append(",");
daysExpression.append(getCronDayOfWeekValue(iterator.next()));
}
}
return String.format("0 %d %d ? * %s", at.getMinute(), at.getHour(), daysExpression.toString());
}
public static String scheduleMonthly(@NotNull LocalTime at, int dayOfMonth) {
checkNotNull("at", at);
return String.format("0 %d %d %d * ?", at.getMinute(), at.getHour(), dayOfMonth);
}
/**
* Converts day of week ordinal from ISO-8601 (MON-SUN) standard to Cron one (SUN-SAT).
*/
private static int getCronDayOfWeekValue(DayOfWeek value) {
TemporalField sundayBaseWeekTemporal = WeekFields.of(DayOfWeek.SUNDAY, 7).dayOfWeek();
return value.get(sundayBaseWeekTemporal);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy