Delay Java program for few secs

Previous
Next

In this post, we will see how to delay java program for few secs.

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.


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

Previous
Next

Add Comment