0

I'd like to effectively "poll" on a JavaFX TableView so that if a job is created in the database by another user the current user would pick it up (let's say every 5 seconds).

I have tried using Timer;

new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        try {
            newI(connection, finalQuery, adminID);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}, 0, 5000);

However this gets the following error: Exception in thread "Timer-0" java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = Timer-0 which I assume means that it is not supported in JavaFX? How am I able to periodically update the TableView in JavaFX?

jbanks
  • 155
  • 1
  • 5
  • 17
  • It doesn't mean it's not supported in JavaFX. It means you are updating something from a background thread instead of from the FX Application Thread. Consider using a [`ScheduledService`](http://docs.oracle.com/javase/8/javafx/api/javafx/concurrent/ScheduledService.html) instead of a timer, and read up on multithreading and JavaFX (e.g. http://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm#JFXIP546 or http://stackoverflow.com/questions/30249493/using-threads-to-make-database-requests or many other sources) – James_D Sep 09 '15 at 14:02

1 Answers1

3

You can use a ScehduleService- something like this...

private class MyTimerService extends ScheduledService<Collection<MyDTO>> {
    @Override
    protected Task<Collection<MyDTO>> createTask() {
        return new Task<Collection<MyDTO>>() {
            @Override
            protected Collection<MyDTO> call() throws ClientProtocolException, IOException {
                   //Do your work here to build the collection (or what ever DTO).
                return yourCollection;
            }
        };
    }
}

    //Instead of time in your code above, set up your schedule and repeat period.    
    service = new MyTimerService () ;
    //How long the repeat is
    service.setPeriod(Duration.seconds(5));
    //How long the initial wait is
    service.setDelay(Duration.seconds(5));

    service.setOnSucceeded(event -> Platform.runLater(() -> {
        //where items are the details in your table
        items =     service.getValue(); 
    }));

    //start the service
    service.start();
purring pigeon
  • 3,869
  • 3
  • 29
  • 62
  • Though you probably want to replace `Void` with a real return type, and have the `call` method return the results of the database query (e.g. a `List`). – James_D Sep 09 '15 at 15:02
  • @James_D do you have any idea why this is happening ? https://stackoverflow.com/questions/44152630/javafx-random-white-empty-pages-issue-in-tableview-while-pagination – Osama Al-Banna May 25 '17 at 09:18