How to Make a Delay in Java

How do I make a delay in Java?

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");
}

How do I make a delay in a for loop in java?

You need to put the Thread.sleep(1000) code inside your loop for, like this:

for(int i = 0; i < Array.length; i++){
System.out.print(Array[i]);
Thread.sleep(1000); // if you prefer, you could put before the System.out...
}

And I recommend that you encapsulate Thread.sleep(1000) with InterruptedException exception handling.

Here are some examples of how you can do it.
Java Delay/Wait

How do I add a delay before a command, without pausing the GUI - JAVA

To run with delay you can use Handler :

 public static void initAfterDelay(Runnable runnable,int delay){
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(runnable, delay);
}

Runnable is your void, and should be used with "this::", that you will shot that method situated in this class, or with the class name and delay in milliseconds, like 100,200 or else value, example:

///if void `petAllDogs` situated in the same class
initAfterDelay(this::petAllDogs,250);

//if void `petAllDogs`situated in the other class, for example Utils
initAfterDelay(Utils::petAllDogs,250);

If you want to delay just some method in Activity/Fragment directly without setting up constructor you can next handler code:

public void initAfterDelay2 (){
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(this::SomeFunction, 500);
}

this can be replaced with SomeActivity::someFunction to access , but SomeMethod should be static and shouldn't have any parameters;

If you want to run void with constructor use the next code in any declared function

     private void some(){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
voidWithParams(parameter 1, parameter 2);
Log.d("Handler", "Running Handler");
}
}, 500);
}

or with lambda expression

private void some(){
final Handler handler = new Handler();
handler.postDelayed(() -> {
voidWithParams(parameter 1, parameter 2);
Log.d("Handler", "Running Handler");
}, 1000);
}

All provided code will have similar result - execution of method after delay



Related Topics



Leave a reply



Submit