package org.oreframework.util.scheduling;
import java.util.Calendar;
/**
* @Title: CronBuilder.java
* @Description: Cron表达式构建器
* @author alvin
* @date 2021年10月23日 下午4:38:35
* @version V1.0
* @Copyright Copyright (c) 2021
*/
public class CronBuilder {
protected static final String ALL_SPEC = "*";
protected static final String NO_SPEC = "?";
protected static final String HYPHEN_SPEC = "-";
protected static final String SLASH_SPEC = "/";
protected static final String COMMA_SPEC = ",";
protected static final String SPACE_SPEC = " ";
private String second = ALL_SPEC;
private String minute = ALL_SPEC;
private String hour = ALL_SPEC;
private String dayOfMonth = ALL_SPEC;
private String month = ALL_SPEC;
private String dayOfWeek = NO_SPEC;
private String year = ALL_SPEC;
private static CronBuilder builder;
private CronBuilder(){
}
public static CronBuilder newBuilder(){
builder = new CronBuilder();
return builder;
}
/**
* 设置秒周期(区间)
* {@code 1-5 * * * * ? *}(每分钟开始的1~5秒,每秒执行)
* @param startSecond 从多少秒开始
* @param endSecond 到多少秒结束
* @return
* @author alvin
* @date 2021年10月23日 下午5:39:31
*/
public CronBuilder setSecondInCycle(int startSecond, int endSecond){
validateSecond(startSecond);
validateSecond(endSecond);
StringBuffer secondCron = new StringBuffer();
secondCron.append(startSecond);
secondCron.append(HYPHEN_SPEC);
secondCron.append(endSecond);
builder.setSecond(secondCron.toString());
return builder;
}
/**
* 设置秒间隔(循环)
* {@code 0/5 * * * * ? *}(每5秒执行)
* @param startSecond 从多少秒开始
* @param intervalSecond 间隔多少秒
* @return
* @author alvin
* @date 2021年10月23日 下午5:40:34
*/
public CronBuilder setSecondInInterval(int startSecond, int intervalSecond){
validateSecond(startSecond);
validateSecond(intervalSecond);
StringBuffer secondCron = new StringBuffer();
secondCron.append(startSecond);
secondCron.append(SLASH_SPEC);
secondCron.append(intervalSecond);
builder.setSecond(secondCron.toString());
return builder;
}
/**
* 设置秒在指定点
* {@code 0,5,10 * * * * ? *}(每分钟的0秒、5秒、10秒执行)
* @param seconds 指定秒数组
* @return
* @author alvin
* @date 2021年10月23日 下午5:43:04
*/
public CronBuilder setSecondInPoint(int...seconds){
if(seconds == null || seconds.length == 0){
builder.setSecond(ALL_SPEC);
return builder;
}
StringBuffer secondCron = new StringBuffer();
for(int second:seconds){
validateSecond(second);
secondCron.append(COMMA_SPEC);
secondCron.append(second);
}
builder.setSecond(secondCron.toString().replaceFirst(COMMA_SPEC, ""));
return builder;
}
/**
* 设置分周期(区间)
* {@code * 1-5 * * * ? *}(每小时开始的1~5分钟,每分钟执行)
* @param startMinute 从多少分开始
* @param endMinute 到多少分结束
* @return
* @author alvin
* @date 2021年10月23日 下午5:39:31
*/
public CronBuilder setMinuteInCycle(int startMinute, int endMinute){
validateMinute(startMinute);
validateMinute(endMinute);
StringBuffer minuteCron = new String
java生成cron表达式构造器
最新推荐文章于 2024-06-14 10:43:27 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)