Cron expression validator

I would like to have custom cron expressions in my program. Are there validators for cron expressions to prevent the user from inserting invalid cron code?

NB I think the cron expression on Quartz.Net is in a smaller format than the one used in UNIX. I would like a Quartz version.

+3


source to share


3 answers


UNIX Cron expressions and quartz expressions are different. Just,

  • On Unix
    • (minute, hour, day, month, day_part, year)
  • In quartz
    • (second, minute, hour, day, month, day_from_program, year)


You can use this to see if the Cron expression is correct.

EDIT: take a look at the CronExpression.ValidateExpression

method.

+3


source


The question has been raised, but now there are more options.



I found this new nuget package NCrontab.Advanced helpful , which is a good replacement for the older NCrontab , adding more functionality and should have a wider range of applications.

0


source


Can use the CronExpression.IsValidateExpression () method with additional regular expression validation using the regular expression.

Example

public static bool IsValidSchedule(string schedule) {

        var valid = CronExpression.IsValidExpression(schedule);
        // Some expressions are parsed as valid by the above method but they are not valid, like "* * * ? * *&54".
        //In order to avoid such invalid expressions an additional check is required, that is done using the below regex.

        var regex = @"^\s*($|#|\w+\s*=|(\?|\*|(?:[0-5]?\d)(?:(?:-|\/|\,)(?:[0-5]?\d))?(?:,(?:[0-5]?\d)(?:(?:-|\/|\,)(?:[0-5]?\d))?)*)\s+(\?|\*|(?:[0-5]?\d)(?:(?:-|\/|\,)(?:[0-5]?\d))?(?:,(?:[0-5]?\d)(?:(?:-|\/|\,)(?:[0-5]?\d))?)*)\s+(\?|\*|(?:[01]?\d|2[0-3])(?:(?:-|\/|\,)(?:[01]?\d|2[0-3]))?(?:,(?:[01]?\d|2[0-3])(?:(?:-|\/|\,)(?:[01]?\d|2[0-3]))?)*)\s+(\?|\*|(?:0?[1-9]|[12]\d|3[01])(?:(?:-|\/|\,)(?:0?[1-9]|[12]\d|3[01]))?(?:,(?:0?[1-9]|[12]\d|3[01])(?:(?:-|\/|\,)(?:0?[1-9]|[12]\d|3[01]))?)*)\s+(\?|\*|(?:[1-9]|1[012])(?:(?:-|\/|\,)(?:[1-9]|1[012]))?(?:L|W)?(?:,(?:[1-9]|1[012])(?:(?:-|\/|\,)(?:[1-9]|1[012]))?(?:L|W)?)*|\?|\*|(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(?:(?:-)(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?(?:,(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(?:(?:-)(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))?)*)\s+(\?|\*|(?:[0-6])(?:(?:-|\/|\,|#)(?:[0-6]))?(?:L)?(?:,(?:[0-6])(?:(?:-|\/|\,|#)(?:[0-6]))?(?:L)?)*|\?|\*|(?:MON|TUE|WED|THU|FRI|SAT|SUN)(?:(?:-)(?:MON|TUE|WED|THU|FRI|SAT|SUN))?(?:,(?:MON|TUE|WED|THU|FRI|SAT|SUN)(?:(?:-)(?:MON|TUE|WED|THU|FRI|SAT|SUN))?)*)(|\s)+(\?|\*|(?:|\d{4})(?:(?:-|\/|\,)(?:|\d{4}))?(?:,(?:|\d{4})(?:(?:-|\/|\,)(?:|\d{4}))?)*))$";

        return valid&& Regex.IsMatch(schedule, regex);
    }

      

0


source







All Articles