Descent and exact time

I am making code where I want a certain accuracy in my time. I use a robot to perform some actions, then I use Thread.sleep(some_time) for some_time to go between actions. But I do not get the best results, because when I look for it, sleep not accurate. What would be the best way to do this? I am referring to Thread.sleep modeling Thread.sleep other methods.

+6
source share
2 answers

Timing in modern OSs is never accurate unless you use a language / framework that was specifically designed for this. However, you can work with reasonable uncertainty on most operating systems. But "reasonable" depends on the problem you are trying to solve.

In Java, Thread.sleep is a very simple implementation that, in my opinion, is used too much. Java offers these basic tools for streaming processing not because they are the best solution, but because they are the main tools. Java also offers many other, more sophisticated tools that can greatly improve your needs.

In the example, if you want โ€œaccurateโ€ time, you can instead use the ScheduledExecutorService , which uses the OS scheduling service, to offer accuracy of at least milliseconds, and often nanoseconds. Although this is not accurate for the nanosecond (despite the suggestion), it will usually be much more accurate than Thread.sleep. But both of them will not be accurate in a heavily overloaded system. If this is enough for your problem, you should go for it. Otherwise, you need a different language / runtime environment.

+7
source

In fact, Java relies on OS tools to implement its timers 1 . The real reason why you don't get more than 1 millisecond precision of timers is because this is the limit of what a typical (non-real-time) OS provides. And even if the temporal resolution was more subtle, the OS still cannot guarantee that the user process will โ€œwake upโ€ exactly at the moment the application requested.

If you need real (i.e., tough) real-time behavior, including high-precision timers and clocks, you need a real-time OS, and you need to run Realtime Java .


1 - These are the same OS objects as the C and C ++ libraries. So just switching to C or C ++ will not help.

+2
source

All Articles