Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handler or a Timer for scheduling fixed rate tasks

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?

like image 537
Mahmoud Avatar asked Jan 10 '14 06:01

Mahmoud


1 Answers

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);
like image 151
Akhil Jain Avatar answered Sep 18 '22 16:09

Akhil Jain