Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduling Repeating Tasks in a Service

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

like image 956
ilan Avatar asked Oct 19 '22 22:10

ilan


1 Answers

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
}
like image 129
Ashwani Avatar answered Oct 22 '22 12:10

Ashwani