Search code examples
javaarduinodelaysleep

Introduce accurate delays in java


I am using my java program to control a motor via Arduino. I plan to introduce the delays in the software itself and not in Arduino. How can I accurately do that since introducing delays using thread.sleep() is very inaccurate? Additionally, I want to pause the delay and upon resume, I want the software to complete the rest of the delay. For example, if I kept a delay for 1000 milliseconds and pause at 700 milliseconds, I want to stop the motor; upon resume, I want to finish the rest of the 300 milliseconds. How efficient it would be if I use a while loop till the System.currentTimeMillis() reaches a specific amount of time?


Solution

  • Make use of ScheduledThreadPoolExecutor. ScheduledExecutorService is an executor service that allows you to schedule future and recurring asynchronous tasks in Java.

    It has been observed that long/ recurring tasks executed using ScheduledExecutorService can result in Memory Leaks. Since Java 7, ScheduledThreadPoolExecutor exposed a new method setRemoveOnCancelPolicy. Make sure this flag is set, as a precautionary measure.

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    // Explicitly call setRemoveOnCancelPolicy on the instance
    executor.setRemoveOnCancelPolicy(true);
    

    As per javaDoc, setRemoveOnCancelPolicy sets the policy on whether cancelled tasks should be immediately removed from the work queue at time of cancellation. This value is by default false