如何在后台任务循环中运行一次代码?

问题描述 投票:0回答:2

我有一个后台任务循环看起来像这样:

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();

这段代码确实每秒循环一次。但是,我想在此代码运行后生成一行代码。

java javafx javafx-8 javafx-2
2个回答
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();

1
投票

只需删除fiveSecondsWonder.setCycleCount(Timeline.INDEFINITE);

© www.soinside.com 2019 - 2024. All rights reserved.