Use java.util.concurrent.TimeUnit
:
TimeUnit.SECONDS.sleep(1);
Sleep for one second or
TimeUnit.MINUTES.sleep(1);
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
][1] and either [scheduleAtFixedRate
][2] or [scheduleWithFixedDelay
][3].
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");
}