This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Java in General and the fly likes Timer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Timer" Watch "Timer" New topic


Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
When I use
Timer t = new Timer(true);
t.schedule( (new Task(),1000);
public class Task {
public void run()
FileOutputStream f = new FileOutputStream ("c:/Kish.log");
PrintWriter pw = new PrintWriter(f);
pw.print("Timer is working");
Nothing is getting printed in the file. But if I use new Timer(false) , it is printing in the file and the prompt, but waits forever since it has started a user thread.
But why does the daemon not writing to the file. Am i missing somethig here.
Thanks for your time.

Regards,<BR>V. Kishan Kumar
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Using new Timer(true), what happens is that your program schedules the task and then gets to the end of the main() method (or whatever method you're running from). That method completes (still about one second before the Task will execute) and the JVM checks to see if there are any non-daemon threads still active. There aren't, so the JVM exits. That's the whole point of having a daemon thread - it doesn't prevent the JVM from executing.
For a single task, the easiest way to get the effect you're looking for would be to forget the Timer nad just put a Thread.sleep(1000) in front of the code you want to delay. For multiple delayed tasks, you might use a non-daemon Timer, and create one more Task whose job is to call the Timer's cancel() method after all other tasks have run.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Timer
It's not a secret anymore!