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

Ely*_*ian 3 java cron timer

我遇到了这个问题:

我有一个文本字段,

应该写一个 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

然后用普通计时器运行它。(但那是后来的:))

请帮忙。提前致谢。

Ely*_*ian 5

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

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]);
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您将 cron 表达式发送到该函数,它将从中生成一个 shedule 表达式,但它不适用于所有 cron 表达式,但对大多数

这是适用于 cron 表达式中各个位置的方法

*    works 
-    works
,    works
/    works
last works (only in the part Day Of Month)
Run Code Online (Sandbox Code Playgroud)

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

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