0

How to compare two cron expressions. We have a condition like we need to compare two cron expressions and need yo check whether both are equal or not

Eg: "0 0/1 * 1/1 * ? *" = "0 0/1 * 1/1 * ? *" then i need to proceed otherwise need to throw error.

Vikram R
  • 99
  • 2
  • 9
  • That expressions are stings. Why you do not compare the strings? – Jens Apr 28 '15 at 07:26
  • 2
    if(cron1.equals(cron2)) { //do stuff } else { throw new Exception("Crons do not match") } – JohannisK Apr 28 '15 at 07:29
  • If you don't want to compare Strings, but the next valid time (in case the crons are different but might result in the same time) maybe this post is usefull? http://stackoverflow.com/questions/26632880/compare-cron-expression-with-current-time – JohannisK Apr 28 '15 at 07:32

2 Answers2

1

I guess you can go with something like this:

    String str1 = "0 0/1 * 1/1 * ? *";
    String str2 = "0 0/1 * 1/1 * ? *";
    if (str1.equals(str2)) {
        // do what you want
    } else {
        throw new Exception("Strings do not match");
    }
Rufi
  • 2,529
  • 1
  • 20
  • 41
0

The question is valid, though the example is bad. Consider the following cases:

cron1 = "* * * * MON"//unix
cron2 = "*/1 * * * 1"//unix
cron3= "0 * * * *"//unix
cron4="0 * * * * MON *"//quartz
//now we compare crons
cron1.equivalent(cron2) -> true
cron1.equivalent(cron3) -> false
cron1.equivalent(cron4) -> true

If you are looking for some library that would allow you to perform such comparisons, have a look at cron-utils

After parsing a cron expression, will create a Cron object, which has a method to compare crons.

sashimi
  • 1,224
  • 2
  • 15
  • 23