views:

2552

answers:

3

I found similar questions asked here but there weren't answers to my satisfaction. So rephrasing the question again-

I have a task that needs to be done on a periodic basis (say 1 minute intervals). What is advantage of using Timertask & Timer to do this as opposed to creating a new thread that has a infinite loop with sleep?

Code snippet using timertask-

TimerTask uploadCheckerTimerTask = new TimerTask(){

 public void run() {
  NewUploadServer.getInstance().checkAndUploadFiles();
 }
};

Timer uploadCheckerTimer = new Timer(true);
uploadCheckerTimer.scheduleAtFixedRate(uploadCheckerTimerTask, 0, 60 * 1000);

Code snippet using Thread and sleep-

Thread t = new Thread(){
 public void run() {
  while(true) {
   NewUploadServer.getInstance().checkAndUploadFiles();
   Thread.sleep(60 * 1000);
  }
 }
};
t.start();

I really don't have to worry if I miss certain cycles if the execution of the logic takes more than the interval time.

Please comment on this..

Thanks,
-Keshav

+4  A: 

The advantage of TimerTask is that it expresses your intention much better (i.e. code readability), and it already has the cancel() feature implemented.

Note that it can be written in a shorter form as well as your own example:

TimerTask uploadCheckerTimer = new Timer(true).scheduleAtFixedRate(
    new TimerTask(){
      public void run() { NewUploadServer.getInstance().checkAndUploadFiles(); }
    }, 0, 60 * 1000);
Zed
A: 

Timer/TimerTask also takes into account the execution time of your task, so it will be a bit more accurate. And it deals better with multithreading issues (such as avoiding deadlocks etc.). And of course it is usually better to use well-tested standard code instead of some homemade solution.

MartinStettner
A: 

There's one crucial argument against managing this task using Java threads and sleep method. You are using while(true) to stay indefinitely in the loop and hibernate the thread by putting to sleep. What if NewUploadServer.getInstance().checkAndUploadFiles(); takes up some synchronized resources. Other threads will be unable to access these resources, starvation may happen which can slow down your whole application. These kinds of errors are hard to diagnose and it's a good idea to prevent their existance.

The other aproach triggers the execution of the code that matters to you, i.e. NewUploadServer.getInstance().checkAndUploadFiles(); by calling the run() method of your TimerTask while letting other threads using the resources in the meanwhile.

Boris Pavlović