Execute task synchronized with the clock

2

I would like to run a task synchronized with the android clock.

  

For example:   in the second 0, then in the second 10, 20, 30, 40 and 50.
  I do not want to run every 10 seconds, I want to run in these exact seconds.

Is there a way to do this?

    
asked by anonymous 10.03.2016 / 21:02

1 answer

2

To do this you can use the AlarmManager class and the setRepeating method, however in the documentation of this method it is said that it is easier and more efficient to use Handler s.

In class Handler you schedule Runnable s to run in the future and also in a certain time. The Handler#postAtTime method receives a Runnable and a time based on the Android runtime, for example, to schedule every 10 seconds, do:

final AtomicLong tick = new AtomicLong(SystemClock.uptimeMillis()
        + 10000L); // timestamp de 10 segundos no futuro

mHandler = new Handler(); // sem acesso a UI Thread
// mHandler = new Handler(Looper.getMainLooper()); // handler ligado a UI Thread
                                                   // ou seja, pode modificar a UI
mHandler.postAtTime(new Runnable() {

    @Override
    public void run() {
        // reagendar-se daqui a 10 segundos
        mHandler.postAtTime(this, tick.addAndGet(10000L));

        // TODO: realizar tarefa
    }
}, tick.get());

You only need to create a mechanism to get the exact time and then increase the tick .

I hope I have helped.

Some useful links:

11.03.2016 / 02:08