Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Timer and TimerTask

Status
Not open for further replies.

PureNSimple

Programmer
Oct 2, 1998
13
US
Hi
I am trying to schedule a recurring task using Timer and TimerTask classes. What I could not understand is how to schedule my task for an indefinite time. I am creating a Timer object. Then I ask it to schedule a TimerTask by passing it an instance of my TimerTask subclass. What I wish is to execute the TimerTask every two hours forever. However, I am having trouble setting this up. Here is the code

Timer timer = new Timer(true);
//create a mailtask
MailTask timerTask = new MailTask(null);
String[] list = new String[] {"pureNSimple@tek-tips.com"};
timerTask.setRecipients(Arrays.asList(list));
//schedule task
timer.schedule(timerTask, 0, 1000*60*60*2);
try {
Thread.currentThread().sleep(1000*60*60*4); problem...the main thread will terminate after 4 hours and with it the scheduled task will cease working
}
catch (Exception ex) {
}
Any idea of how to schedule a task to work forever will be highly appreciated.

Regards,
Pure [hourglass]
 
How about just doing this:

Code:
while (true)
{
   try {
       Thread.currentThread().sleep(1000); 
   }
   catch (Exception ex) {}
}

Or if you need to cancel it from another thread...

Code:
boolean cancel = false;
while (true)
{
   if (cancel)  break;
   try {
       Thread.currentThread().sleep(1000); 
   }
   catch (Exception ex) {}
}
 
Thanks Idarke. That was real helpful.

Actually I was looking for a solution in the Timer class itself. But yes you are right we can wrap it up in an infinite loop to achieve the goal.

Regards,
Pure
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top