Reputation: 4239
I have a Trade
class which contains a property currentPrice
, which downloads price data from a website using getPricedata()
method. The Trade
object will show up as a table row in TableView
. Now, my task: is to
getPricedata()
method to grab data from internet, populate the currentPrice
cell, whenever the object is created. getPricedata()
method to every 1 minute after the object has been created and update table cell. Below is the basic structure of my code. But I have no idea how to implement this ?
Which package do I need ? Task
? Service
? ScheduledService
?
public class Trade{
private DoubleProperty currentPrice;
// need thread here
public double getPricedata(){
.......
}
}
Upvotes: 1
Views: 247
Reputation: 209330
Use a ScheduledService<Number>
, whose Task<Number>
's call()
method retrieves and returns the value. Then you can either register an onSucceeded
handler with the service, or just bind the Trade
's currentPrice
to service.lastValue()
. Call setPeriod(..)
on the service (once) to configure it to run every minute.
Since the currentPrice
is being set from the service, you should only expose a ReadOnlyDoubleProperty
from your Trade
class (otherwise you might try to call currentPriceProperty().set(...)
or setCurrentPrice(...)
, which would fail as it's bound).
I would do something like
public class Trade {
private final ReadOnlyDoubleWrapper currentPrice ;
private final ScheduledService<Number> priceService = new ScheduledService<Number>() {
@Override
public Task<Number> createTask() {
return new Task<Number>() {
@Override
public Number call() {
return getPriceData();
}
};
}
};
public Trade() {
priceService.setPeriod(Duration.minutes(1));
// in case of errors running service:
priceService.setOnFailed(e -> priceService.getException().printStackTrace());
currentPrice = new ReadOnlyDoubleWrapper(0);
currentPrice.bind(priceService.lastValueProperty());
startMonitoring();
}
public final void startMonitoring() {
priceService.restart();
}
public final void stopMonitoring() {
priceService.cancel();
}
public ReadOnlyDoubleProperty currentPriceProperty() {
return currentPrice.getReadOnlyProperty();
}
public final double getCurrentPrice() {
return currentPriceProperty().get();
}
private double getPriceData() {
// do actual retrieval work here...
}
}
(Code just typed in here without testing, but it should give you the idea.)
Upvotes: 2