Java wait seconds or delay Java program for few secs

Delay java program by few seconds

In this post, we will see how to delay java program for few secs or wait for seconds for java program to proceed further.

We need to delay a java programs in many situation where we want to wait for some other task to finish.

There are multiple ways to delay execution of java program or wait for seconds to execute it further.


Using Thread.sleep

Sleep method causes current thread to pause for specific duration of time.We can use Thread’s class sleep static method delay execution of java program.

Here is sample code to the same.

Output:

Going for sleep for 5 secs
Resumed after 5 secs

Please note that Unit of time is milliseconds for sleep method, that’s why we have passed 5000 for 5 secs delay.

Sleep method is not always accurate as it depends on system timers and schedulers.


Using TimeUnit.XXX.sleep method

You can use java.util.concurrent.TimeUnit to sleep for specific duration of time.

For example:
To sleep for 5 mins, you can use following code

TimeUnit.MINUTES.sleep(5)

To sleep for 10 sec, you can use following code

TimeUnit.SECONDS.sleep(10)

Output:

Going for sleep for 10 secs
Resumed after 10 secs

Internally TimeUnit.SECONDS.sleep will call Thread.sleep method. Only difference is readability.


Using ScheduledExecutorService

You can also use ScheduledExecutorService which is part of executor framework. This is most precise and powerful solution to pause any java program.

I would strongly recommend to use ScheduledExecutorService in case you want to run the task every secs or few secs delay.

For example:
To run the task every second, you can use following code.

executorService.scheduleAtFixedRate(DelayFewSecondsJava::runTask, 0, 1, TimeUnit.SECONDS);
Here DelayFewSecondsJava is classname and runTask is method name of that class.

Output:

Running the task each second
Running the task each second
Running the task each second
Running the task each second

Frequently asked questions on Java wait seconds

How to wait for 5 seconds in java?

You can simply use below code to wait for 5 seconds.

How to wait for 1 seconds in java?

You can simply use below code to wait for 1 seconds.

How to pause for 5 seconds in java?

Pause and wait are synonyms here, so you can simply use below code to pause for 5 seconds.

That’s all how to delay java program for few seconds or how to wait for seconds in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *