6

I am working on an application which requires it to go online every x minutes and check for some new data. To prevent heavy network and data usage the task should run at fixed rate, but what is the best approach to use for this kind of solution ? A Handler or a Timer object?

McCygnus
  • 4,187
  • 6
  • 34
  • 30
Mahmoud
  • 353
  • 1
  • 3
  • 14

6 Answers6

5

There are some disadvantages of using Timer

  • It creates only single thread to execute the tasks and if a task takes too long to run, other tasks suffer.
  • It does not handle exceptions thrown by tasks and thread just terminates, which affects other scheduled tasks and they are never run.

Whereas on Other hand, ScheduledThreadPoolExecutor deals properly with all these issues and it does not make sense to use Timer.. There are two methods which could be of use in your case

  • scheduleAtFixedRate(...)

  • scheduleWithFixedDelay(..)

    class LongRunningTask implements Runnable {
    
      @Override
      public void run() {
        System.out.println("Hello world");
      } 
    }
    
    ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
    long period = 100; // the period between successive executions
    exec.scheduleAtFixedRate(new LongRunningTask (), 0, duration, TimeUnit.MICROSECONDS);
    long delay = 100; //the delay between the termination of one execution and the commencement of the next
    exec.scheduleWithFixedDelay(new MyTask(), 0, duration, TimeUnit.MICROSECONDS);
    

And to Cancel the Executor use this - ScheduledFuture

// schedule long running task in 2 minutes:
ScheduledFuture scheduleFuture = exec.scheduleAtFixedRate(new MyTask(), 0, duration, TimeUnit.MICROSECONDS);

... ...
// At some point in the future, if you want to cancel scheduled task:
scheduleFuture.cancel(true);
Akhil Jain
  • 13,872
  • 15
  • 57
  • 93
0

You should use a Service and an AlarmReceiver Like This That's what they're for. If you use a Timer or any other mechanism in your Activity and you set your data to update every "few minutes" there's a good chance the user will not be in your app and Android may very well clean it up, leaving your app *not updating. The Alarm will stay on till the device is turned off.

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236
0

if you are looking for a good performance and less battery consume, you should consider an Alarm manager integrated with broadcast Reciever that will call a service in X time and let it do the work then turn it off again.

However, using timer or handler you need to let your service run in background at all times. unless, you want it to get data while the application is running therefore you dont need a service.

if your choice is whether handler or timer, then go with timer because it is more simpler and can do the job in better performance. handlers usually used to update the UI using Runnable or Messeges.

Coderji
  • 7,655
  • 5
  • 37
  • 51
  • yes I need to load news when the user runs the application, but I want to check if there is some new data arrived new, I used the AlarmManager once but it stills run even the application or not internet is found, once I registered it – Mahmoud Jan 10 '14 at 06:45
  • you can add a check for internet before running the alarm manager or in the service before start fetching the news – Coderji Jan 10 '14 at 06:48
0

Maybe Alarm Manager, timer, handler or ScheduledThreadPoolExecutor.

Take a look at this:

Scheduling recurring task in Android

It depends on whether updates will occur while the user is not in the app (will the checks halt as soon as the user leaves to send an SMS, for example, or should polling continue?) can the check run on the UI thread then spawn the loading from a service or AsyncTask or other thread? Maybe none of that matters...

Community
  • 1
  • 1
Jim
  • 10,172
  • 1
  • 27
  • 36
0

If you don't need to update anything while the user is not viewing the app, go with timer. Service would be an overkill. Here is a sample code to achieve this:

final Runnable updateRunnable = new Runnable() {
    public void run() {
        // Fetch the date here in an async task 
    }
};

final Handler myHandler = new Handler();
private Timer myTimer;

private void updateUI() {
   myHandler.post(updateRunnable);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  // ... other things here

  myTimer = new Timer();
  myTimer.schedule(new TimerTask() {
     @Override
     public void run() {
        updateUI(); // Here you can update the UI as well
     }
  }, 0, 10000); // 10000 is in miliseconds, this executes every 10 seconds

  // ... more other things here

}
Arda Yigithan Orhan
  • 1,062
  • 11
  • 18
0

Alarm manager or handler. If you use handler and postDelayed, your process doesn't have to stay active all the time.

In fact using Handler is officially recommended over Timer or TimerTask: http://android-developers.blogspot.ru/2007/11/stitch-in-time.html

aragaer
  • 17,238
  • 6
  • 47
  • 49