• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Timer and TimerTask

 
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check the API for scheduleAtFixedRate(TimerTask, long, long). The middle argument doesn't mean what you think it means.
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Thanks all, I have learnt one though .. never start anything new in the middle of nights.
Thanks again.
 
I child proofed my house but they still get in. Distract them with this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic