Calling a method every 10 minutes in Android [closed]

I have an activity with a button. When I press that button, a method should be called every 10 minutes.

I am trying to do so using a Handler and a Timer. But couldn’t get the result.

Answer

Create a Timer object and give it a TimerTask that performs the code you’d like to perform.

Timer timer = new Timer ();
TimerTask hourlyTask = new TimerTask () {
    @Override
    public void run () {
        // your code here...
    }
};

// schedule the task to run starting now and then every hour...
timer.schedule (hourlyTask, 0l, 1000*60*60);   // 1000*10*60 every 10 minut

The advantage of using a Timer object is that it can handle multiple TimerTask objects, each with their own timing, delay, etc. You can also start and stop the timers as long as you hold on to the Timer object by declaring it as a class variable or something.

Leave a Reply

Your email address will not be published. Required fields are marked *