jQuery in Action, 3rd edition
The moose likes Java in General and the fly likes Timer and TimerTask Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Timer and TimerTask" Watch "Timer and TimerTask" New topic

Timer and TimerTask

Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
Why dosent the following code work as intended.
public class testTimer {
public static void main(String args[]) {
Timer t = new Timer(false);
t.scheduleAtFixedRate((new Ta()),System.currentTimeMillis(),1000);

public class Ta extends TimerTask {
public void run()
{try {
FileOutputStream fw = new FileOutputStream("D:/timer.txt",true);
PrintWriter pw = new PrintWriter(fw);
pw.println("Timer is working");
}catch(Exception e) {}
System.out.println("Timer is working");
when testTimer is run the timertask Ta is not scheduled...the run method is not called. Is there any mistake Iam doing here.

Regards,<BR>V. Kishan Kumar
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Check the API for scheduleAtFixedRate(TimerTask, long, long). The middle argument doesn't mean what you think it means.

"I'm not back." - Bill Harding, Twister
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Kishan,
The problem is this line of code:

The second parameter is the delay before the timer is called. What you are passing is the current number of millsecs since the epoch (Jan. 1, 1970), I was a junior in high school! So for your program to work as expected, you'll have to wait over 30 years before that timer starts firing. So if you don't want to waste 30 years of your life, change the second parameter to something like 0-1000.
Hope this helps,
Michael Morris

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
Thanks all, I have learnt one though .. never start anything new in the middle of nights.
Thanks again.
I agree. Here's the link: http://aspose.com/file-tools
subject: Timer and TimerTask
It's not a secret anymore!