验证 cron 表达式在 Java 中是否有效
我正在使用 Quartz 用 Java 编写一个调度应用程序。我正在使用 CronTrigger,但我的 cron 表达式在计划之前会输入到数据库中,并且基于用户输入。
有没有办法可以在捕获 cron 表达式时验证它们是否有效?我宁愿这样做并向用户提供适当的错误消息,而不是等到调度程序运行并且在尝试创建触发器时收到 ParseException。这可能是在用户输入数据几天后。
I'm writing a scheduling application in Java using Quartz. I'm using the CronTrigger, but my cron expressions are entered into a database before they are scheduled and are based on user input.
Is there a way I can verify that the cron expressions are valid when I capture them? I'd rather do this and give the user an appropriate error message than wait until the scheduler is run and I get a ParseException when I try and create the trigger. Which could be days after the user inputs the data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
难道你不能简单地创建一个触发器而不实际执行它吗?如果出现 ParseException,您可以简单地提供适当的反馈。如果表达式没问题,则将表达式持久化到数据库。
编辑:或者简单地这样做:
Can't you simply create a trigger without actually executing it? You could simply give appropriate feedback in case of a ParseException. If the expression is okay, persist the expression to DB.
Edit: or simply do this:
我修改了 @ph4r05 添加的以下 代码 以生成正则表达式;这是正则表达式:
这是java代码:
我绝不是正则表达式专家,但至少这似乎适用于quartz 文档
I've modified the following code added by @ph4r05 to generate a regex as well; here's the regex:
Here's the java code:
I'm by no means a regex expert, but at least this seems to work on all the examples given by the quartz documentation
您可以使用 cron-utils
不仅会检查 cron 是否有效,而且您可以从不同的 cron 格式转换为目标格式(例如:如果用户输入 Unix cron 表达式,您可以轻松转换为 Quartz 并将该格式保存到数据库)。
下面我们提供一些片段:
You could use cron-utils
Not only will check the cron is valid, but you could convert from different cron formats to the target one (ex.: if the user inputs a Unix cron expression, you could easily convert to Quartz and persist that one to DB).
Below we provide some snippets:
我在Github上的“QuartzNet”项目中找到了以下正则表达式。我认为这可能是 Quartz 用来验证 cron 表达式的方法。
链接: https://github.com/quartznet/ quartznet/blob/master/src/Quartz/Xml/job_scheduling_data_2_0.xsd
I found the following regular expression in the "QuartzNet" project on Github. I think it may be what Quartz uses to validate cron expressions.
Link: https://github.com/quartznet/quartznet/blob/master/src/Quartz/Xml/job_scheduling_data_2_0.xsd
如果您使用的是
org.quartz
,您可以按如下方式验证Cron表达式:引用自官方API文档CronExpression 类:
If you are using
org.quartz
, you can validate a Cron expression as follows:Quoted from official API document Class CronExpression:
如果你没有 org.quartz 包,你也可以使用 org.springframework.scheduling.support.CronSequenceGenerator.isValidExpression(@Nullable String expression) 方法。
you can also use org.springframework.scheduling.support.CronSequenceGenerator.isValidExpression(@Nullable String expression) method if you have not org.quartz package.