• Post Reply Bookmark Topic Watch Topic
  • New Topic

Schedular class.. Which is a better option?

 
Sajee Joseph
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
I need to have a schedular which runs every 2 hours.
Below i have given 2 options to achieve this. Please tell me which is the better option.
Option 1
==========
class MySchedular extends Thread
{
public void run()
{
while(true)
{
// My code goes here
this.sleep(1000*60*60*2);
}
}
}
Option 2
=========
class MyTimerTask extends TimerTask
{
public void run()
{
// My code goes here
}
}
public class TimerTest
{
public static void main(String args[])
{
Timer timer = new Timer();
timer.schedule(new MyTimerTask(), 1000*5, 1000*5);
}
}
Please tell me which is a better option among these 2.
Is there any other good option?
Regards,
Sajee
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd vote for Timer. You're reusing some (presumably) sound code from Sun rather than writing and testing your own. You may not need it (yet) but Timer could handle any number of scheduled tasks on different schedules. Before I found Timer I wrote my own to do all that, and it turned out to be a fair amount of work. I wouldn't make you do it again!
 
Adrian Yan
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree with Stan, Timer is better for your requirement. One thing you need to make sure is:

This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method. (From javadoc).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!