As the title, is there a way to get the Timer working under the threshold of a millisecond?
My question is similar the following one, but it is intended for Java: Thread.Sleep for less than 1 millisecond
If you want to sleep, Thread.sleep
has 2 methods, one of which accepts nanoseconds. If you want to schedule a task, you can use a ScheduledExecutorService
which schedule
methods can use nanoseconds too.
As explained by @MarkoTopolnik, the result will most likely not be precise to the nanosecond.
Thread.sleep(long millis, int nanos)
Also check out this answer with details on issues with this on Windows.
You could wait on an object that nobody will notify...
synchronized (someObjectNobodyWillNotify) {
try {
someObjectNobodyWillNotify.wait(0, nanosToSleep);
}
catch (InterruptedException e) {
Thread.interrupt();
}
}
(In this scenario, I'm guessing spurious wakeups are okay. If not, you need to record your System.nanoTime()
at the start and wrap the wait
in a loop that checks that enough time has elapsed.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With