我有一个要求,我只需要在工作日的上午9点到下午5点之间运行Java程序。时区将始终为UTC。该节目应在上午9点整开始,下午5点前结束。如果它不能在下午5点之前完成,那么它应该睡眠到第二天08:59:59。如果下一天是周末,那么应该从周一开始。
文章difference in seconds between two dates using joda time?解释了如何获得两个预定义日期之间的秒数差,但我总是想计算下一个工作日上午9点和当前时间之间的差值。
我正在考虑使用Thread.sleep()来计算两个日期之间的时间差。有没有Joda Time api可以用来计算两个日期之间的时间差?
我已经尝试获取当前的纪元和第二天上午9点的纪元,计算这两个纪元之间的差值,并将该值用于Thread.sleep,但它有点混乱。
下面是我使用的伪代码
getNextDayEpoch函数包含if/else代码,用于使用Determine if date is weekday/weekend java确定是工作日还是周末
根据是工作日还是周末,我得到了相应的时值。
currentEpoch = getCurrentEpoch()
nextDayEpoch = getNextDayEpoch()
difference = nextDayEpoch - currentDayEpoch
try {
Thread.sleep(difference);
} catch (InterruptedException e) {
e.printStackTrace();
}你能建议一些更好的方法吗?
发布于 2019-08-09 22:33:34
也许您想了解有关调度ScheduledExecutorService的知识,您也可以看看Quartz-Framwork
我会拿石英来做这个。
发布于 2019-08-09 22:46:58
如果您当前在项目中使用spring,可以尝试使用带cron参数的@Scheduled批注
@Scheduled(cron = "0 0 1 * * ?")
public void doThing() {
//...
}发布于 2019-08-10 00:01:31
Joda-Time项目现在位于maintenance-mode中。Joda-Time的创建者Stephen Colebourne继续领导JSR310及其在java.time类中的实现。
设定你的极限。
LocalTime ltStart = LocalTime.of( 9 , 0 ) ;
LocalTime ltStop = LocalTime.of( 17 , 0 ) ; 获取你想要的时区的当前时刻。
ZoneId z = ZoneOffset.UTC ; // Or ZoneId.of( "Africa/Casablanca" ) or such.
ZonedDateTime now = ZonedDateTime.now( z ) ;比较一天的时间。
if( now.toLocalTime().isBefore( ltStart() ) {
// Wait until start
Duration d = Duration.between( now , now.with( ltStart ) ) ;
// Use that duration to schedule task.
}查看当前时刻是否在工作时间内。
if( ( ! now.toLocalTime().isBefore( ltStart ) && ( now.toLocalTime().isBefore( ltStop ) { // do work }如果现在在停止时间之后,使用plusDays添加一天,调用with将tomorrow设置为上午9点,并计算等待时间的持续时间。
你想要下一个工作日。您可以使用DayOfWeek枚举自己编写跳过星期六和星期日的代码。但我建议将库(也由Stephen Colebourne领导)添加到您的项目中。它提供了TemporalAdjuster的nextWorkingDay实现。
// If the current time is on or after the stop time…
if( ! now.toLocalTime().isBefore( ltStop ) ) {
TemporalAdjuster ta = org.threeten.extra.Temporals.nextWorkingDay() ;
ZonedDateTime nextStart = now.with( ltStart ).with( ta ) ;
Duration d = Duration.between( now , nextStart ) ;
// Use duration to schedule next execution.
}在对三种可能性(启动前、启动-停止期间和停止后)进行测试之后,我建议添加一个"else“作为防御性编程,以确保您的代码是正确的。
差分(
Thread.sleep);
让线程休眠是可行的,但这是一种相对粗糙的方式。
了解Java中的Executors框架,以简化任务调度工作。参见Oracle Tutorial。和搜索堆栈溢出,因为这已经被多次报道过了。
https://stackoverflow.com/questions/57432153
复制相似问题