If your synchronization operation involves interface updates these tasks must be performed in the FX Thread, otherwise such an error will occur: Not on FX application thread
Assuming this is the case, to perform a task every X time on the main thread we have the Scheduledservice, which works as follows:
The Scheduledservice is a Service which will Automatically Restart itself after a Successful Execution, and under some conditions will Restart Even in case of Failure. A 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();
This way you can put a period that is equivalent to the time of execution of the update code in average + 5 seconds. There would be no need to check if the process is already occurring and to allocate a thread to count the 5 seconds.
Important remarks: If the execution of the task takes longer than the specified period the delay is skipped and the next schedule is executed immediately.
You make it every 5 seconds, open an application instance?
– Marco Giovanni
No. My application will be running. And every 5 seconds, it will call a method that will run the application. Then I would check if there was a synchronization happening or not, if it exists, I hope it ends to start another, if it does not exist, it starts the method. I could tell?
– José Allison
tries to use the class
Timer
java– Julio Cesar
this link (http://www.dsc.ufcg.edu.br/~Jacques/cursos/map/html/threads/timer.html) has an example of how to use the classes
Timer
andTimerTask
– Julio Cesar
Thanks @Juliocesar, I’ll take a look and already put a feedback. :)
– José Allison
@Juliocesar made using timer and is working, however, I could not find a way to identify if the method is still running.
– José Allison
@Joséallison, as well, did not understand..
– Julio Cesar
Imagine the scenario: Started the synchronization method (method 01), and the data synchronization process exceeded the 5 seconds that set for my method 01, hence method 01 would start again, and there is already an execution of it. So what I want to avoid is this, that it starts to synchronize if an instance of the method is running. I understood?
– José Allison
Try to use flags, when method_01 started activating the flag in true and when it ends it returns to the normal state, at the time of executing the synchronization method asks for the flag, depending on the value executes or does not execute
– Julio Cesar