如何在某些时间窗口中运行方法
我有一个微服务会收到一条消息,类似的东西:
["00:12", "12:20", "15:40"]
是否有任何开箱即用的解决方案可以允许每天给定时间运行的方法? 使用Spring的Cron不涉及更改运行时的时间。我需要使用一个更灵活的选项(更改运行时,多次启动)
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Spring具有
@scheduled
注释。有几种配置它的方法,一种方法是像Unix Cron作业一样配置它。例如:
此处的任务计划在每个月的15天在上午10:15执行。
但是,也有一种方法可以在运行时动态配置延迟或速率,例如这样(取自baeldung.com):
行
即时NextExecution Time = ...
可以用自己的逻辑代替设置下一个执行时间,就像从数组中解析时间一样。看一下有关它的贝尔登教程: https://wwww.baeldung-com/spring-spring-scheduled -tasks
也请在这里查看cron符号: https://www.netiq.com/documentation/cloud-manager-2-5/ncm-reference/data/bexyssf.html
Spring has the
@Scheduled
annotation. There a several ways to configure it, one way is to configure it like unix cron job.For example like this:
The task here is scheduled to be executed at 10:15 AM on the 15th day of every month.
But there a also ways to configure the delay or rate dynamically at Runtime, for example like this (taken from baeldung.com):
The line
Instant nextExecutionTime = ...
could be replaced with your own logic for setting the next execution time, like parsing the times from your array.Take look at this baeldung tutorial about it: https://www.baeldung.com/spring-scheduled-tasks
Also take look here for the cron notation: https://www.netiq.com/documentation/cloud-manager-2-5/ncm-reference/data/bexyssf.html
最好的解决方案(几乎总是如此)取决于您的基础架构必须工作的上下文。
您可以使用
@scheduled
(即),但在集群中表现不佳(通常只有一个节点运行作业)。我将建议在简单,效率和可靠性之间保持良好平衡的解决方案。稍后,我将讨论它的一些属性。
建议的解决方案:
这种方法的值得注意的属性:
Begin trans;从时间> = NOW = 0订单按时间限制。
The best solution depends (as almost always) on the context in which your infrastructure will have to work.
You can use
@Scheduled
(i.e. Spring Scheduled Task running in clustered environment ) but it does not perform well in clusters (there is usually only one node running jobs).I am going to suggest a solution with a good balance between simplicity, efficiency and reliability. I will discuss some of its properties later.
Suggested solution:
Noteworthy properties of this approach:
begin trans; select 1 id from jobs where time >= now and running = 0 order by time limit 1; ... update jobs set running = 1 where id = ?; ...; commit trans
).