Home > Java > javaTutorial > How to Best Implement Delays and Scheduling in Java?

How to Best Implement Delays and Scheduling in Java?

Mary-Kate Olsen
Release: 2024-12-18 21:57:11
Original
393 people have browsed it

How to Best Implement Delays and Scheduling in Java?

Creating Delays in Java

In Java, introducing delays can be achieved through various methods. When aiming for a fixed interval delay within a loop, java.util.concurrent.TimeUnit offers the sleep method. To pause for a specified number of seconds, one can use TimeUnit.SECONDS.sleep(1);. However, this approach poses a potential issue called drift, which causes deviations from the intended delay with each cycle.

For flexible control and task scheduling, ScheduledExecutorService emerges as a more suitable solution. The methods scheduleAtFixedRate and scheduleWithFixedDelay allow for precise task execution based on a specified delay interval.

In Java 8, to execute myTask every second using scheduleAtFixedRate:

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

For Java 7 compatibility:

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

The above is the detailed content of How to Best Implement Delays and Scheduling in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template