JavaFX2: Can I pause a background job / service?

I am trying to set up a background service that will bulk download transaction data from a csv file. This background service will be triggered from the action of the menu item associated with the method in the controller / presenter class.

Often so, some data appears in the csv file, for which the main data cannot be found in the database, this usually leads to a crash and load failure.

In such cases, I would like the background service to pause its processing and call a dialog from the presenter class to enter user input. User input will be used to add a master line to the database, after which the background service should resume from where it was stopped (not from the beginning of the csv file, but from the line that caused the error).

Can this be implemented in JavaFX, possibly using the javafx.concurrent API? How can i do this?

+11
multithreading concurrency service javafx-2 task
Feb 18 '13 at 16:40
source share
1 answer

Decision

When your background process is faced with a situation where it requires the user to request input, use the FutureTask executed in the Platform.runLater in the showAndWait dialog prompt in the JavaFX application thread. In the background, use futureTask.get to pause the background process until the user enters the necessary values ​​to allow the process to continue.




Code snippet example

Here is the gist of the code for this approach, which can be placed inside the call method of your background process:

String nextText = readLineFromSource(); if ("MISSING".equals(nextText)) { updateMessage("Prompting for missing text"); FutureTask<String> futureTask = new FutureTask( new MissingTextPrompt() ); Platform.runLater(futureTask); nextText = futureTask.get(); } ... class MissingTextPrompt implements Callable<String> { private TextField textField; @Override public String call() throws Exception { final Stage dialog = new Stage(); dialog.setScene(createDialogScene()); dialog.showAndWait(); return textField.getText(); } ... } 



Application example

I created a small, complete, sample application to demonstrate this approach.

Sample application output:

promptingtaskdemooutput

Sample Output Explanation

Lines read without missing values ​​are simply brown. Lines with a quick value entered have a pale green background. Fourteen lines were read, the background task has already been suspended on the 6th line, where the value is missing. The user was prompted to indicate a missing value (to which the user entered xyzzy ), then the process continued until line 14 disappeared and the background task was paused again and a prompt dialog box appeared.

+19
Feb 19 '13 at 21:36
source share



All Articles