我有一个后台任务循环看起来像这样:
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();
这段代码确实每秒循环一次。但是,我想在此代码运行后生成一行代码。
简单的解决方案分两步。
创建一个布尔变量:
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();
只需删除fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);