在我们的应用程序中,我们有一些任务必须按计划运行。
我们使用 TimerService
来安排它们应该运行的时间,并且它们一直运行良好,直到我们安排其中一个在星期六运行。
如果计划配置中的星期几值包含 6
,则由于 timerService.getTimers().iterator().next(),在星期六,任务每秒运行一次.getNextTimeout()
返回过去的日期。
例如,如果任务计划在星期一到星期六的 3 月 17 日星期六 08:00:01 运行,那么它会在星期六的 08:00:01 运行,并且 getNextTimeout()
方法返回下一次执行时间为 3 月 12 日星期一 08:00:01,这会导致任务再次运行并再次返回相同的下一次执行时间,依此类推。
这是我编写的一个测试代码片段,它展示了这个问题
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.*;
@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class TestTimer {
Logger logger = LoggerFactory.getLogger(TestTimer.class);
@Resource
private TimerService timerService;
@PostConstruct
public void initTimer() {
TimerConfig tc = new TimerConfig();
tc.setInfo("TimerTest");
tc.setPersistent(false);
timerService.createCalendarTimer(
new ScheduleExpression()
.second(1)
.minute(0)
.hour(8)
.dayOfMonth("*")
.dayOfWeek("1-6"),tc);
logger.info("Timer: "+tc.getInfo());
}
@Timeout
public void execute() {
logger.info("Executing "+TestTimer.class);
}
}
我看不出我编写的代码有任何错误,这让我相信该错误可能是由于错误或部署应用程序的 Glassfish 服务器配置不当造成的。
最佳答案
关于Java TimerService 下一次执行时间是过去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49358541/