I'd like to create MIDI clock which works basically like a normal clock. It simply ticks and counts its ticks. Now I have read quite a few times that Thread.sleep() isn't accurate at all. So correcting it every every few cycles ensures that it is stable in the long term?
My Clock Class
public class Clock implements Runnable { long beatsPassed = 0; double bpm = 120; // default double beatLength; // default boolean running = false; Clock(int bpm) { this.bpm = bpm; this.beatLength = 60.0 / bpm; this.running = true; } public void run() { int beatLengthInMS = (int) (this.beatLength * 1000); long baseTime = System.currentTimeMillis(); // long corrected = 1; try { while (running) { // check delay every 9 beats // mod == 0 lets it the first time through which causes a negative timeout if (this.beatsPassed % 10 == 9) { // corrected = (System.currentTimeMillis() - baseTime) - (beatLengthInMS * 9); Thread.sleep(beatLengthInMS + ((System.currentTimeMillis() - baseTime) - (beatLengthInMS * 9))); baseTime = System.currentTimeMillis(); } else { Thread.sleep(beatLengthInMS); } this.beatsPassed++; // System.out.println(corrected); } } catch (InterruptedException e) { e.printStackTrace(); } } } Now I have measured actually quite steady times. It always adds about 6-9ms. Am I forgetting something fundamental or is my approach wrong? Also great would be if you could tell me a more performant way to this?
sleep()then you're attacking the problem from the wrong direction. Usesleep(), but on each tick measure the time elapsed from your start time and update your clock according to the time passed.