• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Timer and TimerTask

 
Kishan Kumar
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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");
pw.close();
}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.
Thanks
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check the API for scheduleAtFixedRate(TimerTask, long, long). The middle argument doesn't mean what you think it means.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
SCJP2
 
Kishan Kumar
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks all, I have learnt one though .. never start anything new in the middle of nights.
Thanks again.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic