aspose file tools*
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 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Timer" Watch "Timer" New topic
Author

Timer

Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
Hi,
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");
System.out.println("Timer");
pw.close();
}
}
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
Wanderer
Sheriff

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: http://aspose.com/file-tools
 
subject: Timer
 
Similar Threads
checking runtime errors
constructing a PrintWriter object
Need help writing a text file
About PrintWriter with println and write
Writing an Empty Line in a File....