Wait for a method to run out so that it can be re-run again [closed]

1

I'm developing a data synchronizer, basically the synchronizer will every 5 seconds check if there is data to be synchronized.

However, my question is how do I do when the synchronization is happening, it does not start a new synchronization, ie, a synchronization process will have to start, finish, wait the 5 seconds before being able to start a new one synchronization. Anyone have an idea how to do it?

    
asked by anonymous 14.08.2017 / 14:02

1 answer

1

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.

    
14.08.2017 / 16:57