Java Forum / General / December 2005
Java Timer
sconeek - 30 Nov 2005 03:45 GMT Hi all,
I am writing a Java app, where I need to wait for 10 seconds after a condition holds good and then check if the same condition still holds true and if yes then do something.
Essentially I have this, if (mDt.getTime() == lsEtTSt.getTime()) { // wait for 10 seconds
// check for the condition again
// Do something }
I dont want to use Thread.sleep. If somebody could suggest a loop or something which goes on for 10seconds that would be really great.
thanks.
sconeek - 30 Nov 2005 04:11 GMT I think the timer class might help me. I am thinking of even creating a loop for 10 seconds. but what should i do within the loop for that time. any help please.
Prashant Parashar - 01 Dec 2005 06:24 GMT Thread.sleep() is best. Forget Timer or loop to introduce the delay.
Thread.sleep would take least resource (or none). Timer will require a new thread (thus the memory). Loop will eat up all the CPU time.
Thomas Hawtin - 01 Dec 2005 20:58 GMT > Thread.sleep() is best. Forget Timer or loop to introduce the delay. > > Thread.sleep would take least resource (or none). Timer will require a > new thread (thus the memory). Loop will eat up all the CPU time. I prefer Object.wait. In order to get a program with sleep to exit, say, in a timely fashion, you need to use Thread.interrupt. Thread.interrupt comes with a host of problems, including disruption of class loading.
I may be in a minority on this one.
Tom Hawtin
 Signature Unemployed English Java programmer http://jroller.com/page/tackline/
sconeek - 02 Dec 2005 00:36 GMT the main purpose of me doing the wait is that, the system is doing something while the program is waiting (or sleeping) and after that time has elapsed I want to double check the information received and then perform action based on that second information.
I do not want to perform any action on the first set of input, as I would like to double check that information and then do something. I hope this helps. The main point of the wait process is to wait for x number of seconds and then check for information again, and if that information matches what I am after then I will do something.
I have tried using thread.sleep but the information actually gets updated while the thread is sleeping, I want it to do nothing till x number of seconds and then check again for information and if satisified with second level of information, do something.
i would really appreciate all help I can get.
Chris Smith - 02 Dec 2005 17:41 GMT > I have tried using thread.sleep but the information actually gets > updated while the thread is sleeping, I want it to do nothing till x > number of seconds and then check again for information and if > satisified with second level of information, do something. You want to suspend the entire process, rather than just the current thread? There is no good way to do that.
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Luc The Perverse - 02 Dec 2005 13:46 GMT >> I have tried using thread.sleep but the information actually gets >> updated while the thread is sleeping, I want it to do nothing till x [quoted text clipped - 3 lines] > You want to suspend the entire process, rather than just the current > thread? There is no good way to do that. I doubt that is what he meant.
I think he is looking for some kind of an input interrupt system. Where the input is coming from, I don't know because he hasn't told us.
I think I finally understand what he is trying to ask. He wants to wait up to a specific amount of time for something to happen, the loop would be used for checking if something had happened. It seems like a reasonable request, if one has never heard of the "right" way of doing it.
Now - I have never done any significant multithreaded Java application. Is it possible to interrupt sleep directly without killing the thread, or is there a better function to use? (I know in MFC C++ there were Semaphores and mutex objects, and you could wait for them to be in a triggered state.)
-- LTP
:) Chris Smith - 03 Dec 2005 02:18 GMT > Now - I have never done any significant multithreaded Java application. Is > it possible to interrupt sleep directly without killing the thread, or is > there a better function to use? (I know in MFC C++ there were Semaphores > and mutex objects, and you could wait for them to be in a triggered state.) I don't remember enough of MFC to recall exactly how MFC wrapped the Windows API here. As far as the API itself, though, the equivalent to Win32 mutexes and critical sections are synchronized blocks, used in different ways. The equivalents of events are Object.wait and Object.notify (as implemented in certain ways, and of course combined with synchronized blocks as they always are).
Semaphores are slightly more complex and not available directly in the language, but they can be easily built from the monitor functions above. Beginning with Java 1.5, the java.util.concurrent package contains an implementation of semaphores. Also, Java 1.5 contains an implementation of mutexes (known as locks) that are NOT tied to lexical scope in the language in the manner that synchronized blocks are.
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Luc The Perverse - 02 Dec 2005 15:10 GMT >> Now - I have never done any significant multithreaded Java application. >> Is [quoted text clipped - 17 lines] > of mutexes (known as locks) that are NOT tied to lexical scope in the > language in the manner that synchronized blocks are. If my ignorance is obvious you can tell me to shutup . . but . . .
I followed you up until this point "that are NOT tied to lexical scope in the language in the manner that synchronized blocks are."
-- LTP
:) Chris Smith - 03 Dec 2005 03:19 GMT > If my ignorance is obvious you can tell me to shutup . . but . . . > > I followed you up until this point "that are NOT tied to lexical scope in > the language in the manner that synchronized blocks are." No problem. With synchronized blocks, you are required to designate a block in which a monitor/lock is acquired. That block is either a whole method or some block within that method. When the block is entered, then monitor is acquired; and when you leave, the monitor is released. This is somewhat convenient because you can't forget to release the monitor.
However, it's also slightly limited. Imagine, for example, that I'm implementing an interpreter for some scripting language. Imagine that the scripting language has explicit commands called "lock" and "unlock" that acquire and release monitors. I can't implement this with simple synchronized blocks in Java, because when I release the monitor depends on some future user input, and NOT on when I leave a block of Java code. Using locks from Java 1.5's java.util.concurrent.locks package, though, I can do this. I just call lock() in response to the lock operation and unlock() in response to the unlock operation. Poorly formed script code can lead to forgetting to release a lock, but that is the script's problem, not mine.
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Luc The Perverse - 03 Dec 2005 16:58 GMT >> If my ignorance is obvious you can tell me to shutup . . but . . . >> [quoted text clipped - 19 lines] > can lead to forgetting to release a lock, but that is the script's > problem, not mine. LOL. I thought I had accomplished something when I made a C++ class that tied a Mutex object to a lexical scope - not the other way around :)
I can see where both could be useful however.
Oh BTW I get it now ;)
-- LTP
:) hiwa - 30 Nov 2005 04:17 GMT Do you have some reason for not using java.util.Timer?
sconeek - 30 Nov 2005 04:19 GMT I wouldnt mind using that either. i just need to know how to implement it.
Luc The Perverse - 30 Nov 2005 05:18 GMT >I wouldnt mind using that either. i just need to know how to implement > it. LOL
Here is an example :)
import java.lang.Thread;
public class BeerSong implements Runnable { Thread runner; BeerSong(){ if (runner == null) { //start the song runner = new Thread(this); runner.start(); } } public void run() { int beerNum = 99; String word = "bottles";
while (beerNum > 0 && runner != null){ WaitAMoment(); if (beerNum == 1) word = "bottle"; System.out.println(beerNum + " " + word + " of beer on the wall"); System.out.println(beerNum + " " + word + " of beer."); System.out.println("Take one down"); System.out.println("Pass it around."); beerNum = beerNum - 1; if (beerNum > 0) System.out.println(beerNum + " " + word + " of beer on the wall"); else System.out.println("No more bottles of beer on the wall"); }
} protected void WaitAMoment() { try { Thread.sleep(300); } catch (InterruptedException e) { }; } public static void main (String[] args) { new BeerSong(); } }
I like to put my sleep into it's own function :)
Of course, you don't need to make a special thread to wait.
You could just insert this code
try { java.lang.Thread.currentThread().sleep(10000); } catch (Exception e) { // e.printStackTrace(); }
Just replace the 10000 with the number of milliseconds you want to wait :)
This is much more efficient than a loop.
-- LTP
:) sconeek - 30 Nov 2005 05:39 GMT I have tried using Thread.sleep() but I would like to use a loop of some kind, as i dont want to try it that way. any other ideas?. something which is not very resource intensive and all it does is loop a variable for 10 secs and once thats over does what i want it to do.
sconeek - 30 Nov 2005 05:43 GMT I want to try something like this, for (int i=0;i<10000;i++) { not sure what to do while its looping???? } Then do whatever.
any help on what should go inside the for loop and if this will actually loop for 10secs or not. thanks to all who reply.
Knute Johnson - 30 Nov 2005 05:54 GMT > I want to try something like this, > for (int i=0;i<10000;i++) { [quoted text clipped - 4 lines] > any help on what should go inside the for loop and if this will > actually loop for 10secs or not. thanks to all who reply. You asked how to do it and even got some examples. Now you are telling us you want to do it with a loop. The reason you aren't getting a loop as an answer is that isn't the way to do it. Use Thread.sleep() or use java.util.Timer but forget the loop.
 Signature Knute Johnson email s/nospam/knute/
sconeek - 30 Nov 2005 06:13 GMT ok my bad. can you tell me whats the best approach with java.util.Timer. thanks again. I will try and attempt it in the meantime.
Luc The Perverse - 01 Dec 2005 05:18 GMT *snip*
You said you want to wait.
If there is some reason you are trying to use a loop - some specific thing you are trying to accomplish then maybe you need to relate that better to use so we are able to help you.
I can imagine a "loop for a specific amount of time" scenario. Let's say you wanted to calculate an irrational value to a certain number of digits, in a finite amount of time, or calculate the best chess move (this may be a more logical example). You could allot the computer a certain number of seconds to perform the task and have it loop until the time was expired.
But that is not what you said. You said you wanted a delay. A delay is never better implemented with a loop than a sleep call.
Of course we are resisting to tell you how to do it, because . . . we are afraid that you are going to do it that way. It would be better if you could explain why you want to use a loop, and/or if we could explain to you why a loop is a bad idea.
-- LTP
:) Roedy Green - 30 Nov 2005 06:30 GMT >I want to try something like this, >for (int i=0;i<10000;i++) { > not sure what to do while its looping???? >} >Then do whatever. The problem with this approach is you will gobble up all the CPU time to accomplish nothing. That was the way you did things in DOS when there were no other tasks that could use the CPU.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
zero - 30 Nov 2005 12:40 GMT >>I want to try something like this, >>for (int i=0;i<10000;i++) { [quoted text clipped - 5 lines] > to accomplish nothing. That was the way you did things in DOS when > there were no other tasks that could use the CPU. Which is also why for example old DOS games can't run on new computers. The time needed to loop is to hardware dependent.
 Signature Beware the False Authority Syndrome
Brandon McCombs - 01 Dec 2005 04:06 GMT > I want to try something like this, > for (int i=0;i<10000;i++) { [quoted text clipped - 4 lines] > any help on what should go inside the for loop and if this will > actually loop for 10secs or not. thanks to all who reply. FYI, the iterations in a loop do not equal a millisecond so you can't use them as a timer. It gets executed as fast as the CPU can execute it.
Roedy Green - 30 Nov 2005 06:29 GMT >I am writing a Java app, where I need to wait for 10 seconds after a >condition holds good and then check if the same condition still holds [quoted text clipped - 11 lines] >I dont want to use Thread.sleep. If somebody could suggest a loop or >something which goes on for 10seconds that would be really great. why not sleep? if you have only one test.
The alternative is to use a Timer that get triggered every 10 seconds. The advantage here is you can use the same Timer thread to manage several different periodic tests. See http://mindprod.com/jgloss/timer.html
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|