decprog
decprog

Reputation: 187

JAVAFX: Thread Stop/Start

My app is currently connecting to a web service to obtain data for use in the app. I'm trying to thread this process so that the getWebServiceData() method fires every X seconds. I think my issue here is I'm trying to restart the new thread using the same instance of WebServiceConnect but I cannot think of any other way around it... can anyone help me to structure this so that the checkbox can terminate the thread, then create a new one when reticked?

I can start the thread with ease, its restarting it once it has been terminated. I am trying to achieve this using a checkbox:

WebServiceConnect Class:

public class WebServiceConnect extends Thread {

    private Boolean runThread = true;

    public Boolean getRunThread() {
        return runThread;
    }

    public void setRunThread(Boolean runThread) {
        this.runThread = runThread;
    }

    //the run method comes from the thread class.
    //allows code to be ran in the background.
    public void run() {
        System.out.println("Starting web service thread......");
        try {
            Thread.sleep(6000);
            while(runThread) {
                getWebServiceData();
                System.out.println("The data has been refreshed.");
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(WebServiceConnect.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("terminating thread.....");
            return;
        } catch (IOException ex) {
            Logger.getLogger(WebServiceConnect.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

Main Class:

public class CourseworkThree extends Application {

    private static final List<String> strings = Arrays.asList("2011", "2012", "2013");
    private BarChart BarChart1;
    private CheckBox[] checkBoxesYear;
    WebServiceConnect wsc = new WebServiceConnect();

    @Override
    public void start(Stage primaryStage) throws IOException {
        wsc.start();

        HBox HBox1 = new HBox();
        HBox1.setPadding(new Insets(10, 10, 10, 10));
        HBox1.setSpacing(10);

        //A checkbox with a string caption
        CheckBox cb2 = new CheckBox("Refresh Data?");
        cb2.setSelected(true);
        HBox1.getChildren().add(cb2);

        cb2.setOnAction((event) -> {
            if(!cb2.isSelected()) {
                wsc.setRunThread(false);
                wsc.interrupt();
                System.out.println("You have stopped refreshing data automatically.");
            } else {
                wsc.setRunThread(true);
                wsc.start();

            }
        }); 

Upvotes: 0

Views: 578

Answers (1)

purring pigeon
purring pigeon

Reputation: 4209

Java FX provides the service to handle this type of thing.

For example.

private class KeepSessionAliveService extends ScheduledService<Void> {
        @Override
        protected Task<Void> createTask() {
            return new Task<Void>() {
                @Override
                protected Void call() throws WhatEverException {
                    //Call your code.
                    return null;
                }
            };
        }
    }

Then set up your timing.

private void startPolling() {
        service = new KeepSessionAliveService() ;
        service.setPeriod(Duration.minutes(6));
        service.setDelay(Duration.minutes(6)); //If you want to wait before starting it.

        service.setOnSucceeded(event -> Platform.runLater(() -> {
            //reset back to FX Thread??
        }));

        service.start();
    }

This will schedule your thread to run at the predefined interval. It will run off the FX thread so it won't impact your UI. If you close the app, the Service will shut down on it's own. I use this in my app to keep my session with the server alive - works like a charm.

Upvotes: 2

Related Questions