1

I'm working on a method in a service class in Android Studio.. I used Timer to re-execute the method every one minute.. but the seconds is matter in my case.. when the onStartCommand lunched at for example 13:40:22, the forRoom1() method we will execute and wait one minute so it will be re-executed at 13:41:22..

I want the forRoom1() method to start its first execution at 13:40:00 so after waiting one minute it will re-executed at 13:41:00..

here is my onStartCommand code:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {

forRoom1();

}
}, 0, 60 * 1000);



return START_STICKY;
}

whatever is the current time, the most important thing is to start is first execution at second 00 can you please help me with this?

Shay Kin
  • 2,539
  • 3
  • 15
  • 22
Alhanoof
  • 98
  • 1
  • 2
  • 8

1 Answers1

1

The first step we must know the second of Current time, then the execution is offset by :
(60 - actualSecond)

For that we use this line :

int second = Calendar.getInstance (). get (Calendar.SECOND);

And here we have the second of the current time, we just have to know how much of the seconds (in milliseconds) remaining to arrive at the next 00s

int delay = (60 - second) * 1000;

Now we all have to start our task for that we will use this method:

public void scheduleAtFixedRate (java.util.TimerTask task,
                                 long delay,
                                 long period)

Params:

task – task to be scheduled.

delay – delay in milliseconds before task is to be executed.

period – time in milliseconds between successive task executions.

and this is the compelet Code :

Timer timer = new Timer();

int second = Calendar.getInstance().get(Calendar.SECOND); // get the actual second 

System.out.println(second); // check the current second on this time 

int delay = (60 - second) * 1000; // this is the first delay to start the task

int period = 60000; // the period on millisSecond 

timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        //  start you task here
        // you can check the time by your self with the line below 
        Log.e(TAG, "run: " + Calendar.getInstance().get(Calendar.MINUTE) + ":" + Calendar.getInstance().get(Calendar.SECOND));
    }
}, delay, period);

Note : you can use timer.schedule() method check this answer for more information

Shay Kin
  • 2,539
  • 3
  • 15
  • 22