This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
This is my first post here, so please bear with me.
I want to make my simple program print "Action" 5 times and then stop. The code below will print "Action" once per second forever. If I un-comment the timer.cancel(); it stops before it even prints once. I've tried putting the timer inside a for loop and inside a while loop, but can't make them work.
I'm not having much success with that. The code below causes "Action to be print 5 times immediately, every second (after the 1 second delay). I believe that the 1 second delay in the timer method does not prevent the computer from running through the for loop quickly. So, 5 timers are created in less than a second and they all activate after the one second delay. Also, if the timer.cancel(); is un-commented, the program prints nothing because it ends before the one second delay has run it's course. I've tried a slightly different version of this with the timer.cancel(); placed within an if( count == 4) loop. It also prints nothing.
Perhaps the timer method will not work the way I want it to. Maybe, I need a different method. Any thoughts?
I'm not talking about looping 5 times in the TimerTask. The Timer will call the task, that's its job, not yours. What I'm talking about is to put the "int counter" inside the TimerTask, to increment it when the task is called (i.e in the run() method), and to cancel the timer when the counter reaches 5.
Joined: Jun 29, 2010
O.K. I finally got it. That definitely took longer than it should have.
I was getting an error message with timer.cancel(); , but System.exit(0); worked straight off. I've put the final product below for any rookies (like me) that might look for it.
I was getting an error message with timer.cancel(); , but System.exit(0); worked straight off.
Dooh this.cancel() would do the trick.
Joined: Jun 29, 2010
Ahh. Yes, that does work. I haven't gotten to "this" in my book yet. I see that it stops printing "Action" without stopping the program. I can see how that's probably a better option in most cases. Thanks a lot.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: stopping Timer after certain number of actions