Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Timer

 
Kishan Kumar
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic