Nicholas Muir
Nicholas Muir

Reputation: 3104

Make a TimerTask start at the change of minute

I have a RecyclerView that contains alarms with the day, hours minutes until the next alarm.

I use a timer task that is running a handler/runnable to update the view on a recyclerview sot that the time until the next alarm is up to date. This works fine and updates the RecyclerView every 60 seconds. However I would like it to start exactly on the change of minute and not mid way between the minutes.

I tried below and it runs without error but doesn't change exactly on the minute:

super.onStart();
UpdateTask updater = new UpdateTask(new Handler(), this);

Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.SECOND, 0);

updateTimer.schedule(updater, startTime.getTime(), 60000);

This is the rest of the code just in case it is needed:

// Timer task for updating the minutes on the alarms recyclerview
    private class UpdateTask extends TimerTask {
        Handler handler;
        MainAlarmsFragment ref;

    public UpdateTask (Handler handler, MainAlarmsFragment ref){
        super();
        this.handler = handler;
        this.ref = ref;
    }

    @Override
    public void run() {

        handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ref.updateDisplay();
                    }
                });
        }
    }

Thanks in advance for your help

Upvotes: 0

Views: 160

Answers (2)

Vyacheslav
Vyacheslav

Reputation: 27211

Try this:

super.onStart();
UpdateTask updater = new UpdateTask(new Handler(), this);

updateTimer.schedule(updater, 0, 60000L);// starts immediately

or to improve task schedule use this:

schTaskEx =  Executors.newScheduledThreadPool(1);

        schFuture = schTaskEx.scheduleAtFixedRate(rnb, 0,60000L, TimeUnit.MILLISECONDS);

where rnb is an instance of Runnable interface.

EDIT

in order to delay fixed time use 60000L instead of 0

Upvotes: 1

Stepan Maksymov
Stepan Maksymov

Reputation: 2606

add minute coz set seconds to 0 you make past time.

startTime.add(Calendar.MINUTE,1);
startTime.set(Calendar.SECOND, 0);

Upvotes: 1

Related Questions