有没有创建 Cron 表达式的 Java 代码?

发布于 2024-11-06 10:55:54 字数 1436 浏览 5 评论 0 原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

清欢 2024-11-13 10:55:54

只需从评论中添加“自己创建”即可。

下面是一个示例:提示用户输入值并将它们传递到以下方法中,Javadoc 解释了哪个值允许什么(取自 http://en.wikipedia.org/wiki/Cron#Format)。

这是未经测试的,并且不会验证任何输入字符串,但我确信您可以做到这一点。

/**
 * Generate a CRON expression is a string comprising 6 or 7 fields separated by white space.
 *
 * @param seconds    mandatory = yes. allowed values = {@code  0-59    * / , -}
 * @param minutes    mandatory = yes. allowed values = {@code  0-59    * / , -}
 * @param hours      mandatory = yes. allowed values = {@code 0-23   * / , -}
 * @param dayOfMonth mandatory = yes. allowed values = {@code 1-31  * / , - ? L W}
 * @param month      mandatory = yes. allowed values = {@code 1-12 or JAN-DEC    * / , -}
 * @param dayOfWeek  mandatory = yes. allowed values = {@code 0-6 or SUN-SAT * / , - ? L #}
 * @param year       mandatory = no. allowed values = {@code 1970–2099    * / , -}
 * @return a CRON Formatted String.
 */
private static String generateCronExpression(final String seconds, final String minutes, final String hours,
                                             final String dayOfMonth,
                                             final String month, final String dayOfWeek, final String year)
{
  return String.format("%1$s %2$s %3$s %4$s %5$s %6$s %7$s", seconds, minutes, hours, dayOfMonth, month, dayOfWeek, year);
}

Cron 格式信息取自此处: http://en.wikipedia.org/wiki/Cron#Format< /a>

Just adding on from the comment that says create it yourself.

Here is an example: Prompt the user for the values and pass them into the following method, the Javadoc explains what is allowed in which value (taken from http://en.wikipedia.org/wiki/Cron#Format).

This is untested and doesn't validate any of the input strings, but I'm sure you can do that.

/**
 * Generate a CRON expression is a string comprising 6 or 7 fields separated by white space.
 *
 * @param seconds    mandatory = yes. allowed values = {@code  0-59    * / , -}
 * @param minutes    mandatory = yes. allowed values = {@code  0-59    * / , -}
 * @param hours      mandatory = yes. allowed values = {@code 0-23   * / , -}
 * @param dayOfMonth mandatory = yes. allowed values = {@code 1-31  * / , - ? L W}
 * @param month      mandatory = yes. allowed values = {@code 1-12 or JAN-DEC    * / , -}
 * @param dayOfWeek  mandatory = yes. allowed values = {@code 0-6 or SUN-SAT * / , - ? L #}
 * @param year       mandatory = no. allowed values = {@code 1970–2099    * / , -}
 * @return a CRON Formatted String.
 */
private static String generateCronExpression(final String seconds, final String minutes, final String hours,
                                             final String dayOfMonth,
                                             final String month, final String dayOfWeek, final String year)
{
  return String.format("%1$s %2$s %3$s %4$s %5$s %6$s %7$s", seconds, minutes, hours, dayOfMonth, month, dayOfWeek, year);
}

Cron Format Information taken from here: http://en.wikipedia.org/wiki/Cron#Format

丑丑阿 2024-11-13 10:55:54

我认为你可以使用 cron-utils ,它带来了一个 CronBuilder 类并允许导出为多种格式。该功能从 4.0.0 版本开始可用。

自述文件中的一个示例:

//Create a cron expression. CronMigrator will ensure you remain cron provider agnostic
import static com.cronutils.model.field.expression.FieldExpressionFactory.*;
Cron cron = CronBuilder.cron(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ))
.withYear(always())
.withDoM(between(1, 3))
.withMonth(always())
.withDoW(questionMark())
.withHour(always())
.withMinute(always())
.withSecond(on(0))
.instance();
//Obtain the string expression
String cronAsString = cron.asString();//0 * * 1-3 * ? *
//Migrate to Unix format
cron = CronMapper.fromQuartzToUnix().map(cron);
cronAsString = cron.asString();//* * 1-3 * *

I think you can use cron-utils, which brings a CronBuilder class and allows to export to multiple formats. The feature is available from version 4.0.0 onwards.

An example from the README:

//Create a cron expression. CronMigrator will ensure you remain cron provider agnostic
import static com.cronutils.model.field.expression.FieldExpressionFactory.*;
Cron cron = CronBuilder.cron(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ))
.withYear(always())
.withDoM(between(1, 3))
.withMonth(always())
.withDoW(questionMark())
.withHour(always())
.withMinute(always())
.withSecond(on(0))
.instance();
//Obtain the string expression
String cronAsString = cron.asString();//0 * * 1-3 * ? *
//Migrate to Unix format
cron = CronMapper.fromQuartzToUnix().map(cron);
cronAsString = cron.asString();//* * 1-3 * *
不乱于心 2024-11-13 10:55:54

您可以根据您的需要更改以下实现。

import java.io.Serializable;

public class CronExpressionCreator implements Serializable {

    private static final long serialVersionUID = -1676663054009319677L;

    public static void main(String[] args) {
        CronExpressionCreator pCron = new CronExpressionCreator();
        pCron.setTime("12:00 PM");
        pCron.setMON(true);
        pCron.setStartDate("12-05-2011");
        System.out.println(pCron.getCronExpression());
    }


    public String getCronExpression() {
        String time = getTime();
        String[] time1 = time.split("\\:");
        String[] time2 = time1[1].split("\\ ");

        String hour = "";
        if (time2[1].equalsIgnoreCase("PM")) {
            Integer hourInt = Integer.parseInt(time1[0]) + 12;
            if (hourInt == 24) {
                hourInt = 0;
            }
            hour = hourInt.toString();
        } else {
            hour = time1[0];
        }

        String minutes = time2[0];
        String cronExp = "";
        if (isRecurring()) {
            String daysString = "";
            StringBuilder sb = new StringBuilder(800);
            boolean moreConditions = false;

            if (isSUN()) {
                sb.append("SUN");
                moreConditions = true;
            }

            if (isMON()) {
                if (moreConditions) {
                    sb.append(",");
                }
                sb.append("MON");
                moreConditions = true;
            }

            if (isTUE()) {
                if (moreConditions) {
                    sb.append(",");
                }

                sb.append("TUE");
                moreConditions = true;
            }

            if (isWED()) {
                if (moreConditions) {
                    sb.append(",");
                }

                sb.append("WED");
                moreConditions = true;
            }

            if (isTHU()) {
                if (moreConditions) {
                    sb.append(",");
                }
                sb.append("THU");
                moreConditions = true;
            }

            if (isFRI()) {
                if (moreConditions) {
                    sb.append(",");
                }
                sb.append("FRI");
                moreConditions = true;
            }

            if (isSAT()) {
                if (moreConditions) {
                    sb.append(",");
                }
                sb.append("SAT");
                moreConditions = true;
            }

            daysString = sb.toString();

            cronExp = "0 " + minutes + " " + hour + " ? * " + daysString;
        } else {
            String startDate = getStartDate();
            String[] dateArray = startDate.split("\\-");
            String day = dateArray[0];
            if (day.charAt(0) == '0') {
                day = day.substring(1);
            }

            String month = dateArray[1];

            if (month.charAt(0) == '0') {
                month = month.substring(1);
            }

            String year = dateArray[2];
            cronExp = "0 " + minutes + " " + hour + " " + day + " " + month
            + " ? " + year;

        }
        return cronExp;
    }

    String startDate;
    String time;
    boolean recurring;
    boolean SUN;
    boolean MON;
    boolean TUE;
    boolean WED;
    boolean THU;
    boolean FRI;
    boolean SAT;

    /**
     * @return the startDate
     */
    public String getStartDate() {
        return startDate;
    }

    /**
     * The date set should be of the format (MM-DD-YYYY for example 25-04-2011)
     * 
     * @param startDate
     *            the startDate to set
     */
    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the time
     */
    public String getTime() {
        return time;
    }

    /**
     * The time set should be of the format (HH:MM AM/PM for example 12:15 PM)
     * 
     * @param time
     *            the time to set
     */
    public void setTime(String time) {
        this.time = time;
    }

    public boolean isRecurring() {
        return recurring;
    }

    public void setRecurring(boolean recurring) {
        this.recurring = recurring;
    }

    public boolean isSUN() {
        return SUN;
    }

    public void setSUN(boolean sUN) {
        SUN = sUN;
    }

    public boolean isMON() {
        return MON;
    }

    /**
     * @param mON
     *            the mON to set
     */
    public void setMON(boolean mON) {
        MON = mON;
    }

    public boolean isTUE() {
        return TUE;
    }

    public void setTUE(boolean tUE) {
        TUE = tUE;
    }

    public boolean isWED() {
        return WED;
    }

    public void setWED(boolean wED) {
        WED = wED;
    }

    public boolean isTHU() {
        return THU;
    }

    public void setTHU(boolean tHU) {
        THU = tHU;
    }

    public boolean isFRI() {
        return FRI;
    }

    public void setFRI(boolean fRI) {
        FRI = fRI;
    }

    public boolean isSAT() {
        return SAT;
    }

    public void setSAT(boolean sAT) {
        SAT = sAT;
    }

    public int hashCode() {
        return this.getCronExpression().hashCode();
    }

    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof CronExpressionCreator) {
            if (((CronExpressionCreator) obj).getCronExpression()
                    .equalsIgnoreCase(this.getCronExpression())) {
                return true;
            }
        } else {
            return false;
        }
        return false;

    }

}

You can change the below implementation as per your needs.

import java.io.Serializable;

public class CronExpressionCreator implements Serializable {

    private static final long serialVersionUID = -1676663054009319677L;

    public static void main(String[] args) {
        CronExpressionCreator pCron = new CronExpressionCreator();
        pCron.setTime("12:00 PM");
        pCron.setMON(true);
        pCron.setStartDate("12-05-2011");
        System.out.println(pCron.getCronExpression());
    }


    public String getCronExpression() {
        String time = getTime();
        String[] time1 = time.split("\\:");
        String[] time2 = time1[1].split("\\ ");

        String hour = "";
        if (time2[1].equalsIgnoreCase("PM")) {
            Integer hourInt = Integer.parseInt(time1[0]) + 12;
            if (hourInt == 24) {
                hourInt = 0;
            }
            hour = hourInt.toString();
        } else {
            hour = time1[0];
        }

        String minutes = time2[0];
        String cronExp = "";
        if (isRecurring()) {
            String daysString = "";
            StringBuilder sb = new StringBuilder(800);
            boolean moreConditions = false;

            if (isSUN()) {
                sb.append("SUN");
                moreConditions = true;
            }

            if (isMON()) {
                if (moreConditions) {
                    sb.append(",");
                }
                sb.append("MON");
                moreConditions = true;
            }

            if (isTUE()) {
                if (moreConditions) {
                    sb.append(",");
                }

                sb.append("TUE");
                moreConditions = true;
            }

            if (isWED()) {
                if (moreConditions) {
                    sb.append(",");
                }

                sb.append("WED");
                moreConditions = true;
            }

            if (isTHU()) {
                if (moreConditions) {
                    sb.append(",");
                }
                sb.append("THU");
                moreConditions = true;
            }

            if (isFRI()) {
                if (moreConditions) {
                    sb.append(",");
                }
                sb.append("FRI");
                moreConditions = true;
            }

            if (isSAT()) {
                if (moreConditions) {
                    sb.append(",");
                }
                sb.append("SAT");
                moreConditions = true;
            }

            daysString = sb.toString();

            cronExp = "0 " + minutes + " " + hour + " ? * " + daysString;
        } else {
            String startDate = getStartDate();
            String[] dateArray = startDate.split("\\-");
            String day = dateArray[0];
            if (day.charAt(0) == '0') {
                day = day.substring(1);
            }

            String month = dateArray[1];

            if (month.charAt(0) == '0') {
                month = month.substring(1);
            }

            String year = dateArray[2];
            cronExp = "0 " + minutes + " " + hour + " " + day + " " + month
            + " ? " + year;

        }
        return cronExp;
    }

    String startDate;
    String time;
    boolean recurring;
    boolean SUN;
    boolean MON;
    boolean TUE;
    boolean WED;
    boolean THU;
    boolean FRI;
    boolean SAT;

    /**
     * @return the startDate
     */
    public String getStartDate() {
        return startDate;
    }

    /**
     * The date set should be of the format (MM-DD-YYYY for example 25-04-2011)
     * 
     * @param startDate
     *            the startDate to set
     */
    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the time
     */
    public String getTime() {
        return time;
    }

    /**
     * The time set should be of the format (HH:MM AM/PM for example 12:15 PM)
     * 
     * @param time
     *            the time to set
     */
    public void setTime(String time) {
        this.time = time;
    }

    public boolean isRecurring() {
        return recurring;
    }

    public void setRecurring(boolean recurring) {
        this.recurring = recurring;
    }

    public boolean isSUN() {
        return SUN;
    }

    public void setSUN(boolean sUN) {
        SUN = sUN;
    }

    public boolean isMON() {
        return MON;
    }

    /**
     * @param mON
     *            the mON to set
     */
    public void setMON(boolean mON) {
        MON = mON;
    }

    public boolean isTUE() {
        return TUE;
    }

    public void setTUE(boolean tUE) {
        TUE = tUE;
    }

    public boolean isWED() {
        return WED;
    }

    public void setWED(boolean wED) {
        WED = wED;
    }

    public boolean isTHU() {
        return THU;
    }

    public void setTHU(boolean tHU) {
        THU = tHU;
    }

    public boolean isFRI() {
        return FRI;
    }

    public void setFRI(boolean fRI) {
        FRI = fRI;
    }

    public boolean isSAT() {
        return SAT;
    }

    public void setSAT(boolean sAT) {
        SAT = sAT;
    }

    public int hashCode() {
        return this.getCronExpression().hashCode();
    }

    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof CronExpressionCreator) {
            if (((CronExpressionCreator) obj).getCronExpression()
                    .equalsIgnoreCase(this.getCronExpression())) {
                return true;
            }
        } else {
            return false;
        }
        return false;

    }

}
挽袖吟 2024-11-13 10:55:54

上面 edwardsmatt 提交的代码段无法与 Quartz 的 CronExpression 正常工作。这是一个更正后的版本:

/**
 * Generate a CRON expression is a string comprising 6 or 7 fields separated by white space.
 *
 * @param seconds    mandatory = yes. allowed values = {@code  0-59    * / , -}
 * @param minutes    mandatory = yes. allowed values = {@code  0-59    * / , -}
 * @param hours      mandatory = yes. allowed values = {@code 0-23   * / , -}
 * @param dayOfMonth mandatory = yes. allowed values = {@code 1-31  * / , - ? L W}
 * @param month      mandatory = yes. allowed values = {@code 1-12 or JAN-DEC    * / , -}
 * @param dayOfWeek  mandatory = yes. allowed values = {@code 0-6 or SUN-SAT * / , - ? L #}
 * @param year       mandatory = no. allowed values = {@code 1970–2099    * / , -}
 * @return a CRON Formatted String.
 */
private static String generateCronExpression(final String seconds, final String minutes, final String hours,
                                             final String dayOfMonth,
                                             final String month, final String dayOfWeek, final String year)
{
  return String.format("%1$s %2$s %3$s %4$s %5$s %6$s %7$s", seconds, minutes, hours, dayOfMonth, month, dayOfWeek, year);
}

The snippet submitted by edwardsmatt above doesn't work properly with Quartz's CronExpression. Here's a corrected version that does:

/**
 * Generate a CRON expression is a string comprising 6 or 7 fields separated by white space.
 *
 * @param seconds    mandatory = yes. allowed values = {@code  0-59    * / , -}
 * @param minutes    mandatory = yes. allowed values = {@code  0-59    * / , -}
 * @param hours      mandatory = yes. allowed values = {@code 0-23   * / , -}
 * @param dayOfMonth mandatory = yes. allowed values = {@code 1-31  * / , - ? L W}
 * @param month      mandatory = yes. allowed values = {@code 1-12 or JAN-DEC    * / , -}
 * @param dayOfWeek  mandatory = yes. allowed values = {@code 0-6 or SUN-SAT * / , - ? L #}
 * @param year       mandatory = no. allowed values = {@code 1970–2099    * / , -}
 * @return a CRON Formatted String.
 */
private static String generateCronExpression(final String seconds, final String minutes, final String hours,
                                             final String dayOfMonth,
                                             final String month, final String dayOfWeek, final String year)
{
  return String.format("%1$s %2$s %3$s %4$s %5$s %6$s %7$s", seconds, minutes, hours, dayOfMonth, month, dayOfWeek, year);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文