如何在 Java 中将 CRON 字符串转换为 ScheduleExpression?

2023-12-01

我遇到这个问题:

我有一个文本字段,

应该编写一个 CRON 表达式,然后保存。

现在我需要一种方法来转换 CRON 字符串(以下是一些随机示例:http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html) 到 java ScheduleExpression (http://docs.oracle.com/javaee/6/api/javax/ejb/ScheduleExpression.html)

但是,我不知道该怎么做......

我有一个基于计时器的执行系统,仅运行几天、几周和几个月,但现在我需要实现 CRON 模型,以便执行可以在特定的时间段内运行...

这是一些代码,只是为了支持我:

@Resource
private TimerService timerService;


@Timeout
public void execute(Timer timer) {
    Script s = (Script) timer.getInfo();
    execute(s, true);
    System.out.println("Timer Service : " + s.getScriptId());
    System.out.println("Current Time : " + new Date());
    System.out.println("Next Timeout : " + timer.getNextTimeout());
    System.out.println("Time Remaining : " + timer.getTimeRemaining());
    System.out.println("____________________________________________");
    Date today = new Date();
    if (s.getTimerSetup().getEndDate() <= today.getTime()) {
        stopTimer(s);
    }
}


@Override
public void startTimer(Script s) {
    if (s.getTimerSetup().getTimerRepeat().equals("0")) {
        return;
    }
    s.setStatus(true);
    em.merge(s);
    em.flush();
    if (s.getTimerSetup().getEndDate() > System.currentTimeMillis()) {
        long timeOut = 1L;
        String timerRepeat = s.getTimerSetup().getTimerRepeat();

        if (timerRepeat.equals("1")) {// day
            timeOut = 1000L * 60L * 60L * 24L;
        } else if (timerRepeat.equals("2")) {// week
            timeOut = 1000L * 60L * 60L * 24L * 7L;
        } else if (timerRepeat.equals("3")) {// month
            timeOut = 1000L * 60L * 60L * 24L * 30L;
        } else {
            return; //Here is the part where the cron string is detected
        }

        long initialTimeOut = s.getTimerSetup().getStartDate() - System.currentTimeMillis();

        if (initialTimeOut < 0) {
            long initCheck = initialTimeOut * -1;
            while (initCheck > timeOut) {
                initCheck -= timeOut;
            }
            initialTimeOut = timeOut - initCheck;
        }

        Boolean found = false;
        if (timerService.getAllTimers().size() == 0) {
            System.out.println("Started the timer for the script: " + s.getFileName());
            timerService.createTimer(initialTimeOut, timeOut, s);
        } else {
            for (Timer timer : timerService.getAllTimers()) {
                if (((Script) timer.getInfo()).getScriptId() == s.getScriptId()) {
                    System.out.println("This script's timer was already started!");
                    found = true;
                }
            }

            if (!found) {
                System.out.println("Started the timer for the script: " + s.getFileName());
                timerService.createTimer(initialTimeOut, timeOut, s);
                found = true;
            }
        }
    } else {
        System.out.println("The script's end date has expired");
    }
}

我标记了检测到cron字符串的地方(在if语句中) 我现在需要将字符串转换为 ScheduleExpression。

然后用正常的计时器运行它。 (但那是稍后的事:))

请帮忙。提前致谢。


我找到了答案,但忘了回答,这是对我有用的代码:

private ScheduleExpression parseCronExpressionToScheduleExpression(String cronExpression) {

    if ("never".equals(cronExpression)) {
        return null;
    }

    // parsing it more or less like cron does, at least supporting same fields (+ seconds)

    final String[] parts = cronExpression.split(" ");
    final ScheduleExpression scheduleExpression;

    if (parts.length != 6 && parts.length != 5) {
        scheduleExpression = scheduleAliases.get(cronExpression);
        if (scheduleExpression == null) {
            throw new IllegalArgumentException(cronExpression + " doesn't have 5 or 6 segments as excepted");
        }
        return scheduleExpression;
    } else if (parts.length == 6) { // enriched cron with seconds
        return new ScheduleExpression()
                .second(parts[0])
                .minute(parts[1])
                .hour(parts[2])
                .dayOfMonth(parts[3])
                .month(parts[4])
                .dayOfWeek(parts[5]);
    }

    // cron
    return new ScheduleExpression()
            .minute(parts[0])
            .hour(parts[1])
            .dayOfMonth(parts[2])
            .month(parts[3])
            .dayOfWeek(parts[4]);
}

因此,如果您将 cron 表达式发送到该函数,它将从中创建一个计划表达式,但它不能在所有 cron 表达式上 100% 工作,但在大多数情况下

以下是 cron 表达式中各个位置的工作原理

*    works 
-    works
,    works
/    works
last works (only in the part Day Of Month)

不起作用的是字母,例如 L 和其他字母,至少在我上次检查时不起作用。

希望这能帮助下一个人:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Java 中将 CRON 字符串转换为 ScheduleExpression? 的相关文章

随机推荐