我目前正在处理一个 Spring 项目,该项目的固定速率设置为 30 秒,如下所示:
@Scheduled(fixedRate = 30000)
public void doThings() {
...
...
if(true) {
// How to stop the method from executing the codes below
// until the next 30 seconds interval?
}
...
...
}
该方法当前计划为每 30 秒一次。
它将运行一些代码来确定 if 语句的条件是否为真。
如果不是 true,则也会执行其余代码。
如果为 true,则停止该方法,直到由于计划的 30 秒间隔而再次自动调用该方法,并且该方法再次从头开始运行代码。
在 if 语句中放置正确的行应该是什么? 还是有Spring特定的方法来做到这一点?
谢谢。
您需要在作业中构建状态。 这是一种方法。 当出现"true"语句时,将作业设置为挂起模式。 然后在接下来的 30 秒周期中,挂起>就绪。 然后在运行代码后重置回来。
public class ScheduleTasks {
private static final Logger logger = Logger.getLogger(ScheduleTasks.class);
public enum JobState {
NONE,
PENDING,
READY;
}
JobState jobState = JobState.NONE;
static int x = 0;
@Scheduled(fixedRate = 30000)
public void doThings() {
if (jobState == JobState.PENDING)
jobState = JobState.READY;
// Here I am just simulating your 'true' statement every now and then
x++;
if (x % 3 == 0) {
jobState = JobState.PENDING;
}
logger.info("jobState="+jobState);
if (jobState == JobState.NONE || jobState == JobState.READY) {
logger.info("Executing code");
jobState = JobState.NONE;
}
}
传统上,Java方法的口头禅是"一个入口,一个出口"。有一个return;
来阻止其余代码执行会破坏这个约定,所以我建议不要这样做。相反,您可以执行一些简单的逻辑分析:
@Scheduled(fixedRate = 30000)
public void doThings() {
...
// Analysis for condition
...
if (condition) {
// Do code that only needs to be run if this condition is true
} else {
// Execute for when this is not true
}
}
如果您希望仅在condition
不正确时执行代码,那么只需执行以下操作:
@Scheduled(fixedRate = 30000)
public void doThings() {
...
// Analysis for condition
...
if (!condition) {
// Do code that only needs to be run if this condition is not true
}
}
由于您问题的意图并不完全清楚,如果此示例过于简化,我提前道歉。请添加更多信息以准确清除您要查找的内容。