Cron表达式工具类CronUtil
构建Cron表达式
/**
*
*方法摘要:构建Cron表达式
*@param taskScheduleModel
*@return String
*/
public static String createCronExpression(TaskScheduleModel taskScheduleModel){
StringBuffer cronExp = new StringBuffer("");
if(null == taskScheduleModel.getJobType()) {
System.out.println("执行周期未配置" );//执行周期未配置
}
if (null != taskScheduleModel.getSecond()
&& null != taskScheduleModel.getMinute()
&& null != taskScheduleModel.getHour()) {
//秒
cronExp.append(taskScheduleModel.getSecond()).append(" ");
//分
cronExp.append(taskScheduleModel.getMinute()).append(" ");
//小时
cronExp.append(taskScheduleModel.getHour()).append(" ");
//每天
if(taskScheduleModel.getJobType().getValue() == 1){
if(taskScheduleModel.getBeApart()!=null){
cronExp.append("1");//日
cronExp.append("/");
cronExp.append(taskScheduleModel.getBeApart()+1);//月
cronExp.append(" ");
cronExp.append("* ");
cronExp.append("? ");//周
cronExp.append("*");
}else {
cronExp.append("* ");//日
cronExp.append("* ");//月
cronExp.append("?");//周
}
}
//按每周
else if(taskScheduleModel.getJobType().getValue() == 3){
//一个月中第几天
cronExp.append("? ");
//月份
cronExp.append("* ");
//周
Integer[] weeks = taskScheduleModel.getDayOfWeeks();
for(int i = 0; i < weeks.length; i++){
if(i == 0){
cronExp.append(weeks[i]);
} else{
cronExp.append(",").append(weeks[i]);
}
}
}
//按每月
else if(taskScheduleModel.getJobType().getValue() == 2){
//一个月中的哪几天
Integer[] days = taskScheduleModel.getDayOfMonths();
for(int i = 0; i < days.length; i++){
if(i == 0){
if(days[i]==32){
//本月最后一天
String endMouthCron="0 0 0 L * ?";
return endMouthCron;
}else {
cronExp.append(days[i]);
}
} else{
cronExp.append(",").append(days[i]);
}
}
//月份
cronExp.append(" * ");
//周
cronExp.append("?");
}
//按每年
else if(taskScheduleModel.getJobType().getValue()== 4){
//一个年中的哪几天
Integer[] days = taskScheduleModel.getDayOfMonths();
if(ArrayUtil.isEmpty(days)){
cronExp.append("*");
}else{
for(int i = 0; i < days.length; i++){
if(i == 0){
cronExp.append(days[i]);
} else{
cronExp.append(",").append(days[i]);
}
}
}
//月份
Integer[] months = taskScheduleModel.getMonths();
if (ArrayUtil.isEmpty(months)) {
cronExp.append(" *");
}else{
for (int i = 0; i < months.length; i++){
Integer month = months[i];
if (month > 12){
throw new RuntimeException("月份数据异常: "+ Arrays.toString(months));
}
if(i == 0){
cronExp.append(" ").append(month);
}else{
cronExp.append(",").append(month);
}
}
}
cronExp.append(" ?");
}
else if(taskScheduleModel.getJobType().getValue() == 0){
cronExp.append("* ");//日
cronExp.append("* ");//月
cronExp.append("?");//周
}
}
else {
System.out.println("时或分或秒参数未配置" );//时或分或秒参数未配置
}
return cronExp.toString();
}
生成计划的详细描述
/**
*
*方法摘要:生成计划的详细描述
*@param taskScheduleModel
*@return String
*/
public static String createDescription(TaskScheduleModel taskScheduleModel){
StringBuffer description = new StringBuffer("");
//计划执行开始时间
// Date startTime = taskScheduleModel.getScheduleStartTime();
if (null != taskScheduleModel.getSecond()
&& null != taskScheduleModel.getMinute()
&& null != taskScheduleModel.getHour()) {
//按每天
if(taskScheduleModel.getJobType().getValue() == 1){
description.append("每天");
description.append(taskScheduleModel.getHour()).append("时");
description.append(taskScheduleModel.getMinute()).append("分");
description.append(taskScheduleModel.getSecond()).append("秒");
}
//按每周
else if(taskScheduleModel.getJobType().getValue() == 3){
if(taskScheduleModel.getDayOfWeeks() != null && taskScheduleModel.getDayOfWeeks().length > 0) {
String days = "";
for(int i : taskScheduleModel.getDayOfWeeks()) {
if(i==1){
days += "周日";
}else {
i=i-1;
days += "周" + i;
}
}
description.append("每周的").append(days).append(" ");
}
if (null != taskScheduleModel.getSecond()
&& null != taskScheduleModel.getMinute()
&& null != taskScheduleModel.getHour()) {
description.append(",");
description.append(taskScheduleModel.getHour()).append("时");
description.append(taskScheduleModel.getMinute()).append("分");
description.append(taskScheduleModel.getSecond()).append("秒");
}
}
//按每月
else if(taskScheduleModel.getJobType().getValue() == 2){
//选择月份
if(taskScheduleModel.getDayOfMonths() != null && taskScheduleModel.getDayOfMonths().length > 0) {
String days = "";
for(int i : taskScheduleModel.getDayOfMonths()) {
days += i + "号";
}
description.append("每月的").append(days).append(" ");
}
description.append(taskScheduleModel.getHour()).append("时");
description.append(taskScheduleModel.getMinute()).append("分");
description.append(taskScheduleModel.getSecond()).append("秒");
}
}
return description.toString();
}
构建Cron表达式
/**
* @description: 构建Cron表达式
*
* @return String
* @author panlupeng
*
*/
public static String createLoopCronExpression(int rate, int cycle) {
String cron = "";
switch (rate) {
case 0:// 每cycle秒执行一次
cron = "0/" + cycle + " * * * * ?";
break;
case 1:// 每cycle分钟执行一次
cron = "0 0/" + cycle + " * * * ?";
break;
case 2:// 每cycle小时执行一次
cron = "0 0 0/" + cycle + " * * ?";
break;
case 3:// 每cycle天的0点执行一次
cron = "0 0 0 1/" + cycle + " * ?";
break;
case 4:// 每cycle月的1号0点执行一次
cron = "0 0 0 1 1/" + cycle + " ? ";
break;
case 5:// 每天cycle点执行一次
cron = "0 0 " + cycle+ " * * ?";
break;
default:// 默认每cycle秒执行一次
cron = "0/1 * * * * ?";
break;
}
return cron;
}
枚举类
public enum JobEnum {
EVERY("每天",0),
DAY("日",1),
MONTH("月",2),
WEEK("周",3),
YEAR("年",4),
;
JobEnum(String name,Integer value) {
this.name = name;
this.value = value;
}
private final String name;
private final Integer value;
public Integer getValue() {
return value;
}
public String getName() {
return name;
}
}
TaskScheduleModel
public class TaskScheduleModel {
/**
* 所选作业类型:
* 0 ->每天每次
* 1 -> 每天
* 2 -> 每月
* 3 -> 每周
* 4 -> 年
*/
JobEnum jobType;
/**一周的哪几天*/
Integer[] dayOfWeeks;
/**一个月的哪几天*/
Integer[] dayOfMonths;
/**秒 */
Integer second;
/**分 */
Integer minute;
/**时 */
Integer hour;
/**
* 年
*/
Integer[] months;
/**
* 间隔
*/
Integer beApart;
public Integer[] getMonths() {
return months;
}
public void setMonths(Integer[] months) {
this.months = months;
}
public Integer getBeApart() {
return beApart;
}
public void setBeApart(Integer beApart) {
this.beApart = beApart;
}
public JobEnum getJobType() {
return jobType;
}
public void setJobType(JobEnum jobType) {
this.jobType = jobType;
}
public Integer[] getDayOfWeeks() {
return dayOfWeeks;
}
public void setDayOfWeeks(Integer[] dayOfWeeks) {
this.dayOfWeeks = dayOfWeeks;
}
public Integer[] getDayOfMonths() {
return dayOfMonths;
}
public void setDayOfMonths(Integer[] dayOfMonths) {
this.dayOfMonths = dayOfMonths;
}
public Integer getSecond() {
return second;
}
public void setSecond(Integer second) {
this.second = second;
}
public Integer getMinute() {
return minute;
}
public void setMinute(Integer minute) {
this.minute = minute;
}
public Integer getHour() {
return hour;
}
public void setHour(Integer hour) {
this.hour = hour;
}
}
测试
public static void main(String[] args) {
//执行时间:每天的17时40分00秒 start
TaskScheduleModel taskScheduleModel = new TaskScheduleModel();
taskScheduleModel.setJobType(JobEnum.DAY);//按每天
Integer hour = 17; //时
Integer minute = 40; //分
Integer second = 00; //秒
taskScheduleModel.setHour(hour);
taskScheduleModel.setMinute(minute);
taskScheduleModel.setSecond(second);
//每隔几天执行
taskScheduleModel.setBeApart(1);
String cropExp = createCronExpression(taskScheduleModel);
System.out.println(cropExp + ":" + createDescription(taskScheduleModel));
//执行时间:每天的17时40分00秒 end
taskScheduleModel.setJobType(JobEnum.WEEK);//每周的哪几天执行
Integer[] dayOfWeeks = new Integer[7];
dayOfWeeks[0] = 1;//周日
dayOfWeeks[1] = 2;//周1
dayOfWeeks[2] = 3;//周2
dayOfWeeks[3] = 4;//周3
dayOfWeeks[4] = 5;//周4
dayOfWeeks[5] = 6;//周5
dayOfWeeks[6] = 7;//周6
taskScheduleModel.setDayOfWeeks(dayOfWeeks);
cropExp = createCronExpression(taskScheduleModel);
System.out.println(cropExp + ":" + createDescription(taskScheduleModel));
taskScheduleModel.setJobType(JobEnum.MONTH);//每月的哪几天执行
Integer[] dayOfMonths = new Integer[3];
dayOfMonths[0] = 1;
dayOfMonths[1] = 21;
dayOfMonths[2] = 13;
taskScheduleModel.setDayOfMonths(dayOfMonths);
cropExp = createCronExpression(taskScheduleModel);
System.out.println(cropExp + ":" + createDescription(taskScheduleModel));
taskScheduleModel.setJobType(JobEnum.EVERY);//每天的几点几分几秒开始
cropExp = createCronExpression(taskScheduleModel);
System.out.println(cropExp);
}
0 40 17 1/2 * ? *:每天17时40分0秒
0 40 17 ? * 1,2,3,4,5,6,7:每周的周日周1周2周3周4周5周6 ,17时40分0秒
0 40 17 1,21,13 * ?:每月的1号21号13号 17时40分0秒
0 40 17 * * ?
第二种解析方式
/**
* @author longwei
* @Description 日期时间转Cron表达式
* @date 2022/11/4 18:17
*/
public class DateTimeToCronUtils {
/**
* 每年format格式
*/
public static final String YEAR = "ss mm HH dd MM ? yyyy";
/**
* 每周format格式
*/
public static final String MONDAY = "ss mm HH ? * 1";
public static final String TUESDAY = "ss mm HH ? * 2";
public static final String WEDNESDAY = "ss mm HH ? * 3";
public static final String THURSDAY = "ss mm HH ? * 4";
public static final String FRIDAY = "ss mm HH ? * 5";
public static final String SATURDAY = "ss mm HH ? * 6";
public static final String SUNDAY = "ss mm HH ? * 7";
/**
* 每天format格式
*/
public static final String EVERYDAY = "ss mm HH * * ?";
/**
* 间隔-每天format格式
*/
public static final String INTERVAL_DAY = "0 0 0 1/param * ? ";
/**
* 间隔-每小时format格式
*/
public static final String INTERVAL_HOUR = "0 0 0/param * * ?";
/**
* 间隔-每分钟format格式
*/
public static final String INTERVAL_MINUTE = "0 0/param * * * ? ";
/**
* LocalDateTime格式化为String
*
* @param date LocalDateTime
* @param dateFormat format格式
* @return String
* @author longwei
*/
public static String formatDateByPattern(LocalDateTime date, String dateFormat) {
return DateUtil.format(date, dateFormat);
}
/**
* date格式化为String
*
* @param date date
* @param dateFormat format格式
* @return String
* @author longwei
*/
public static String formatDateByPattern(Date date, String dateFormat) {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
String formatTimeStr = null;
if (date != null) {
formatTimeStr = sdf.format(date);
}
return formatTimeStr;
}
/**
* 时间转换Cron表达式
*
* @param date date
* @param dateFormat format格式
* @return Cron表达式
* @author longwei
*/
public static String getCron(Date date, String dateFormat) {
return formatDateByPattern(date, dateFormat);
}
/**
* 时间转换Cron表达式
*
* @param date date
* @param dateFormat format格式
* @return Cron表达式
* @author longwei
*/
public static String getCron(LocalDateTime date, String dateFormat) {
return formatDateByPattern(date, dateFormat);
}
/**
* 间隔天转换Cron表达式
*
* @param param 天
* @return Cron表达式
* @author longwei
*/
public static String getIntervalDayCron(String param) {
return INTERVAL_DAY.replace("param", param);
}
/**
* 间隔小时转换Cron表达式
*
* @param param 小时
* @return Cron表达式
* @author longwei
*/
public static String getIntervalHourCron(String param) {
return INTERVAL_HOUR.replace("param", param);
}
/**
* 间隔分钟转换Cron表达式
*
* @param param 分钟
* @return Cron表达式
* @author longwei
*/
public static String getIntervalMinuteCron(String param) {
return INTERVAL_MINUTE.replace("param", param);
}
public static void main(String[] args) {
Date date = new Date();
String cron = getCron(date, YEAR);
System.out.println("date-每年执行一次" + cron);
cron = getCron(date, MONDAY);
System.out.println("date-每周一执行" + cron);
cron = getCron(date, EVERYDAY);
System.out.println("date-每天执行" + cron);
System.out.println("------------------------------");
LocalDateTime localDateTime = LocalDateTime.now();
cron = getCron(localDateTime, YEAR);
System.out.println("localDateTime-每年执行一次" + cron);
cron = getCron(localDateTime, MONDAY);
System.out.println("localDateTime-每周一执行" + cron);
cron = getCron(localDateTime, EVERYDAY);
System.out.println("localDateTime-每天执行" + cron);
LocalDate localDate = LocalDate.now();
LocalDateTime dateTime = localDate.atTime(13, 14);
cron = getCron(dateTime, EVERYDAY);
System.out.println("localDateTime-每天指定时间执行" + cron);
cron = getIntervalDayCron("1");
System.out.println("localDateTime-间隔1天执行" + cron);
cron = getIntervalHourCron("2");
System.out.println("localDateTime-间隔2小时执行" + cron);
cron = getIntervalMinuteCron("5");
System.out.println("localDateTime-间隔5分钟执行" + cron);
}
}
文章来源地址https://www.toymoban.com/news/detail-721033.html
文章来源:https://www.toymoban.com/news/detail-721033.html
到了这里,关于java时间解析生成定时Cron表达式工具类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!