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

如何在Java中将CRON字符串转换为ScheduleExpression?,java,timer,cron,Java,Timer,Cron,我遇到了这个问题: 我有一个文本字段 应该编写一个CRON表达式,然后保存 现在我需要一个方法将CRON字符串(这里有一些随机示例:)转换为java ScheduleExpression() 但是,我不知道怎么做 我有一个基于计时器的执行系统,只在几天、几周和几个月内运行,但现在我需要实现CRON模型,以便执行可以在特定的时间段上运行 这里有一个小代码,只是为了支持我: @Resource private TimerService timerService; @Timeout public

我遇到了这个问题:

我有一个文本字段

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

现在我需要一个方法将CRON字符串(这里有一些随机示例:)转换为java ScheduleExpression()

但是,我不知道怎么做

我有一个基于计时器的执行系统,只在几天、几周和几个月内运行,但现在我需要实现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");
    }
}
@Resource
私人TimerService TimerService;
@超时
公共无效执行(计时器){
脚本s=(脚本)timer.getInfo();
执行(s,正确);
System.out.println(“计时器服务:+s.getScriptId());
System.out.println(“当前时间:+新日期());
System.out.println(“下一个超时:+timer.getNextTimeout());
System.out.println(“剩余时间:+timer.getTimeRemaining());
系统.out.println(“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu;
今天日期=新日期();
if(s.getTimerSetup().getEndDate()系统.currentTimeMillis()){
长超时=1L;
字符串timerRepeat=s.getTimerSetup().getTimerRepeat();
如果(timerRepeat.equals(“1”){//day
超时=1000L*60L*60L*24L;
}如果(timerRepeat.equals(“2”){//week
超时=1000L*60L*60L*24L*7L;
}如果(timerRepeat.equals(“3”){//month
超时=1000L*60L*60L*24L*30L;
}否则{
return;//这是检测到cron字符串的部分
}
长initialTimeOut=s.getTimerSetup().getStartDate()-System.currentTimeMillis();
如果(初始化超时<0){
long initCheck=initialTimeOut*-1;
while(初始化检查>超时){
initCheck-=超时;
}
initialTimeOut=超时-初始化检查;
}
布尔值=false;
if(timerService.getAllTimers().size()=0){
System.out.println(“启动脚本的计时器:+s.getFileName());
createTimer(initialTimeOut,timeOut,s);
}否则{
for(计时器:timerService.getAllTimers()){
如果(((脚本)timer.getInfo()).getScriptId()==s.getScriptId()){
System.out.println(“此脚本的计时器已启动!”);
发现=真;
}
}
如果(!找到){
System.out.println(“启动脚本的计时器:+s.getFileName());
createTimer(initialTimeOut,timeOut,s);
发现=真;
}
}
}否则{
System.out.println(“脚本的结束日期已过期”);
}
}
我标记了检测到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表达式发送给函数,它将从中生成一个调度表达式,但它不是100%适用于所有cron表达式,而是大多数cron表达式

下面是对cron表达式中的各个位置起作用的内容

*    works 
-    works
,    works
/    works
last works (only in the part Day Of Month)
不起作用的是字母,如L和其他字母,至少在我上次检查时不起作用


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

为什么不使用,因为我不知道:)你应该稍后了解web app和quartz!但是如果可能的话,我想在没有任何其他技术的情况下完成这项工作……除了quartz之外,我还有什么建议吗?谢谢-我需要创建一个系统,在多个系统中使用来自数据库的CRON语句。您的代码是以压缩方式在Java中运行特别事件的一个补充。@JECarterII很高兴有人发现它很有用:)ScheduleAlias在这里指的是这个的完整版本。