Skip to content
Advertisement

How do I make a delay in Java?

I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.

JavaScript

I want to build a step sequencer.

How do I make a delay in Java?

Advertisement

Answer

If you want to pause then use java.util.concurrent.TimeUnit:

JavaScript

To sleep for one second or

JavaScript

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):

JavaScript

And in Java 7:

JavaScript
Advertisement