How do I make a delay in Java?
Use Thread.sleep(1000)
;
1000
is the number of milliseconds that the program will pause.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
If you want to pause then use java.util.concurrent.TimeUnit
:
TimeUnit.SECONDS.sleep(1);
To sleep for one second or
TimeUnit.MINUTES.sleep(1);
To sleep for a minute.
As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep
.
Further, sleep
isn't very flexible when it comes to control.
For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService
and either scheduleAtFixedRate
or scheduleWithFixedDelay
.
For example, to run the method myTask
every second (Java 8):
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
And in Java 7:
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
myTask();
}
}, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
Use this:
public static void wait(int ms)
{
try
{
Thread.sleep(ms);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
and, then you can call this method anywhere like:
wait(1000);
You need to use the Thread.sleep()
call.
More info here: http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html