Consider the following code:
while(true) { someFunction(); Thread.sleep(1000); }
What I want is that, someFunction() be called once every 10 seconds. But this is not the case. It is being called every second. I tried Thread.wait(1000), but even that doesnt help. I removed of the while part, just kept the body, and at the end wrote :
Thread.start();
But it throwed an exception. Is there any other solution to this?
It's being called every second because you're sleeping for 1000 milliseconds, aka 1 second.
Change it to Thread.sleep(10000) and that'll be better for you.
Alternatively, use
Thread.sleep(TimeUnit.SECONDS.toMillis(10));
which means you don't have to do the arithmetic yourself. (Many APIs now take a quantity and a TimeUnit, but there doesn't appear to be anything like that for Thread.sleep unfortunately.)
Note that this will make the thread unresponsive for 10 seconds, with no clean way of telling it to wake up (e.g. because you want to shut it down). I generally prefer to use wait() so that I can pulse the same monitor from a different thread to indicate "I want you to wake up now!" This is usually from within a while loop of the form
while (!shouldStop())
EDIT: tvanfosson's solution of using a Timer is also good - and another alternative is to use ScheduledExecutorService which can be a bit more flexible (and easier to test).
Thread.sleep() takes the number of miliseconds to sleep. Thus, calling Thread.sleep(1000) sleeps 1000 miliseconds, which is 1 second. Make that Thread.sleep(10000) and it will sleep 10 seconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With