Handler or a Timer for scheduling fixed rate tasks Handler or a Timer for scheduling fixed rate tasks multithreading multithreading

Handler or a Timer for scheduling fixed rate tasks


There are some disadvantages of using Timer

  • It creates only single thread to execute the tasks and if a tasktakes too long to run, other tasks suffer.
  • It does not handle exceptions thrown by tasks and thread just terminates, which affectsother 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 executionsexec.scheduleAtFixedRate(new LongRunningTask (), 0, duration, TimeUnit.MICROSECONDS);long delay = 100; //the delay between the termination of one execution and the commencement of the nextexec.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);


You should use a Service and an AlarmReceiverLike ThisThat'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.


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.