Timer in Java

J

joshivaibhav

Hello,

I am running the following code, but it never terminates:


import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class YetAnotherTimer
{
private static Integer iCount = 0;
public static void main (String args[])
{
int numberOfMillisecondsInTheFuture = 10000; // 10 sec

Date timeToRun = new
Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);

Timer timer = new Timer();

timer.schedule(new TimerTask()
{
public void run()
{
System.out.println("Generating report");
iCount++;
System.out.println("Count is: " + iCount);
}
}, timeToRun);
}
}

It simply waits in the memory. I am looking for functionality where the
timer will execute a task at a predefined time and once the task is
finished, the timer thread will exit. I tried calling the method
cancel() from within the run() method, but still it does not terminate
the timer thread.

Please let me know.

Thanks,

Vaibhav
 
D

Daniel Pitts

joshivaibhav said:
Hello,

I am running the following code, but it never terminates:


import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class YetAnotherTimer
{
private static Integer iCount = 0;
public static void main (String args[])
{
int numberOfMillisecondsInTheFuture = 10000; // 10 sec

Date timeToRun = new
Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);

Timer timer = new Timer();

timer.schedule(new TimerTask()
{
public void run()
{
System.out.println("Generating report");
iCount++;
System.out.println("Count is: " + iCount);
}
}, timeToRun);
}
}

It simply waits in the memory. I am looking for functionality where the
timer will execute a task at a predefined time and once the task is
finished, the timer thread will exit. I tried calling the method
cancel() from within the run() method, but still it does not terminate
the timer thread.

Please let me know.

Thanks,

Vaibhav

Look into the Timer(boolean isDaemon) constructor.
 
J

joshivaibhav

I found the problem:

If I use the timer.cancel(); after the statement:

System.out.println("Count is: " + iCount);

The timer terminates properly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top