If your synchronization operation involves updates to the interface, these tasks must be performed on the FX Thread, otherwise an error of this type will occur: Not on FX application thread
Assuming this is the case, to run a task every X time on the main thread we have ScheduledService , which works as follows:
The ScheduledService is a Service that will automatically restart itself after a successful execution, and under some conditions will restart even in case of failure. The new ScheduledService begins in the READY state, just as a normal Service. After calling start or restart, the ScheduledService will enter the SCHEDULED state for the duration specified by delay.
Executable example:
ScheduledService<Void> sync = new ScheduledService<Void>() {
@Override
protected Task<Void> createTask() {
Task<Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception{
// sua operação de sincronização
return null;
}
};
return task;
}
};
// Thread executa a cada 5 segundos
sync.setPeriod(Duration.seconds(5));
// Início do serviço de sincronização
sync.start();
// Parar a sincronização
sync.cancel();
In this way you can put a period that is equivalent to the execution time of the update code in average + 5 seconds. There would be no need to check if the process is already taking place and not allocate a thread to count the 5 seconds.
Important notes: If the task execution takes longer than the specified period, the delay is skipped and the next schedule is executed immediately.