Androids Calendar.MINUTE not returning correct minute

So I have a loop that I want to poll for data every 5 minutes to keep my api requests to a minimum. The problem is CurrentMin is not updating when minute is on android phone. It starts out right, but then it can't stay relevant. Any ideas how I can make the poll data every 5 minutes?

while (x==false) {
    currentMin= c.get(Calendar.MINUTE); //get the current min

    if (currentMin%5==0) {//poll the data every 5 min
        ***Poll data***



source to share

3 answers

From How to run a method every X seconds :

Use Handler

. Never, and I mean never scheduling tasks using while

Android. Your battery will dry up in a few minutes, you will block your user interface and slow down the application.

Handler h = new Handler();
int delay = 1000; //interval in milliseconds

h.postDelayed(new Runnable(){
    public void run(){
        //pool data
        h.postDelayed(this, delay);
}, delay);




You can try using TimerTask

. A sliding aproach is a pretty bad choice.

Here is an example of using it



Use ScheduledThreadPoolExecutor

like this:

private ScheduledThreadPoolExecutor mScheduleTaskExecutor = new ScheduledThreadPoolExecutor(1);
mScheduleTaskExecutor.scheduleAtFixedRate(yourRequestRunnable, 0, 5, TimeUnit.SECONDS);


And yourRequestRunnable would be something like:

Runnable yourRequestRunnable = new Runnable() {
    // Do your request here


This will ensure that you execute your code at a fixed rate. If you need to do something in the UI after the request completes, just wrap the code that handles the UI changes torunOnUiThread()



All Articles