5

I need to repeat a task every 1 hour in the background (I am sending some info to my server).

  1. I tried to use a service with a post delay handler calling it self.

       handler = new Handler(); 
    runable = new Runnable() { 
    
        @Override 
        public void run() { 
            try{
    
            //sending info to server....
    
            }
            catch (Exception e) {
                // TODO: handle exception
            }
            finally{
                //also call the same runnable 
                handler.postDelayed(this, 1000*60*60); 
            }
        } 
    }; 
    handler.postDelayed(runable, 1000*60*60); 
    

This did not work, in small time interval of 1 minutes it worked fine, when i changed it to 5 minutes it worked for about 5 repetitions and then the timing got wrong and after an hour the service shut down.

  1. i want to try to use a AlarmManager but in the documentation it says "As of Android 4.4 (API Level 19), all repeating alarms are inexact" does anybody know how inexact it is? is it seconds? ,minutes? can i rely on this to work on time?

  2. does anybody have any other suggestions for repeating tasks in a service?

Thanks

ilan
  • 4,402
  • 6
  • 40
  • 76
  • If you want your alarm to set for precise time then use setExact method, then in broadcastreiver set your alarm with same setExact method and call your service. – Chitrang Nov 09 '14 at 07:36
  • The alarmManager doesn't have a setExact function. In the documentation it has but when i press ctrl+space in eclipse i get only set(...), setInexactRepeating(...) and setRepeating(). – ilan Nov 09 '14 at 08:01
  • Have you tried copying that method name, and try to find why it is not supporting? – Chitrang Nov 09 '14 at 20:04
  • http://stackoverflow.com/questions/13115809/asynchronous-repeating-scheduled-task?answertab=active#tab-top – Zar E Ahmer Dec 05 '14 at 07:28

1 Answers1

3

You can use this This Code is for repeated calling on oncreate method or anyother thing

public void callAsynchronousTask() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        onCreate();

                    } catch (Exception e) {

                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}
Ashwani
  • 127
  • 1
  • 4