如何在javafx中设置任务超时?

vzgqcmou  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(324)

我有一个类,有一个方法可以通过usb设备获取数据并将其添加到arraylist中:

public class usbDevice {
    public Task<Void> readData() {
        return new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                //read data through usb device and add it into array;
                return null;
            }
        };
    }
}

我在扩展usb\U设备类的控制器类中按下按钮时调用此方法:

@FXML
void readUSB(ActionEvent event) {
    try {
        Parent root = FXMLLoader.load(getClass().getResource("../resources/loadingPage.fxml"));
        Scene scene = startButton.getScene();

        root.translateXProperty().set(scene.getWidth());
        parent.getChildren().add(root);

        Timeline timeline = new Timeline();
        KeyValue keyValue = new KeyValue(root.translateXProperty(), 0 , Interpolator.EASE_IN);
        KeyFrame keyFrame = new KeyFrame(Duration.millis(100), keyValue);
        timeline.getKeyFrames().add(keyFrame);

        timeline.setOnFinished(event1 -> {
            parent.getChildren().remove(container);
            Task<Void> readTask = readData();
            Thread t = new Thread(readTask);
            t.start();
        });
        timeline.play();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

但有时我会陷入这种方法,我需要重新连接到我的usb设备,如果10秒后,例如,我没有得到数据。我如何设置超时,将重新连接我的usb设备每10秒在这个线程,直到我通过它获得数据?提前谢谢

aiazj4mn

aiazj4mn1#

你可以使用 CompletableFuture :

public class USBDevice {
    public Task<Void> readData() {
        return new Task<Void>() {
            @Override
            protected Void call() throws Exception {

                CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                    //read data through usb device and add it into array;
                });
                try {
                    future.get(10, TimeUnit.SECONDS);
                    // get here if read was successful
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                } catch (ExecutionException ee) {
                    // exception was thrown by code reading usb device
                } catch (TimeoutException te) {
                    // timeout occurred
                }
                return null;
            }
        };
    }
}

相关问题