gpt4 book ai didi

scheduled-tasks - Spring cron 表达式 - 如何获得上次执行时间

转载 作者:行者123 更新时间:2023-12-04 11:46:58 25 4
gpt4 key购买 nike

在 Spring 中,我可以使用以下方法获得 nextExecution 时间:

final CronSequenceGenerator generator = new CronSequenceGenerator(cronExpression);
final Date nextExecutionDate = generator.next(new Date());

但是如何从 cron 表达式中获取最后一次执行时间?

最佳答案

它使用二进制搜索来查找上次执行时间。

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import org.springframework.scheduling.support.CronExpression;

public class CronTest {

@Test
void cronTest() {
CronExpression expression = CronExpression.parse("1 0/10 * * * ?");
ZonedDateTime nextTime = expression.next(ZonedDateTime.now());
assertNotNull(nextTime);
ZonedDateTime prevTime = getPrevTime(expression, nextTime, nextTime.minusDays(1));
assertEquals(nextTime.minusMinutes(10), prevTime);
}

private ZonedDateTime getPrevTime(CronExpression expression, ZonedDateTime nextTime, ZonedDateTime mayPrevTime) {
ZonedDateTime start = mayPrevTime;
ZonedDateTime end = nextTime;
while (start.isBefore(end)) {
ZonedDateTime middle = end.minusSeconds(
TimeUnit.MILLISECONDS.toSeconds(Duration.between(start, end).toMillis() / 2));
ZonedDateTime tmpNextTime = expression.next(middle);
if (Objects.equals(tmpNextTime, nextTime)) {
end = middle.minusSeconds(1);
} else {
start = middle.plusSeconds(1);
}
}
return start;
}
}

关于scheduled-tasks - Spring cron 表达式 - 如何获得上次执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37452087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com