我有一个后台任务循环,如下所示:
Timeline fiveSecondsWonder = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
if (hourNow >= cashCutOff_Start && hourNow <= cashCutOff_End - 1) {
//Run the code once
}
}));
fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);
fiveSecondsWonder.play();
此代码确实每隔一秒钟就使循环。但是,一旦此代码运行,我想使一行代码可执行。
答案 0 :(得分:1)
只需删除fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);
答案 1 :(得分:0)
分两个步骤的简单解决方案。
创建一个布尔变量:
private boolean hasRun = false;
在时间轴中添加if语句:
Timeline fiveSecondsWonder = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
//check if code has run before
if(!hasRun){
//this will run only once
//by setting hasRun = true;
hasRun=true;
//add your code here...
}
//this code will run in every KeyFrame
//add your code here...
}));
fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);
fiveSecondsWonder.play();