If you want a high frequency yet accurate frequency, I wouldn't use a timer.
I did something much like this once in Delphi, providing quick pulses to a stepper motor. I was at liberty to chew up as much CPU time as I wanted for this, so I ran a tight loop that checked Windows' high precision timer until the right amount of time had passed, and then did the action I needed.
It's not quite as convenient in Java, but I'd recommend a similar approach, using System.nanoTime()
.
You may find you missed the last time mark. If so, deal with it somehow. Either hurry and do your action anyway, or do whatever needs doing to compensate for the error - maybe wait for an entire character space to pass, or whatever. Also, you may want to modify the time interval to the next event. Whatever it takes to accurately deal with the normal jitter, in other words.
If you don't do a lot of object creation in your loop, there's no sensible reason why your garbage collector should kick in, so your timing has a reasonable chance of remaining accurate.
Update
Jonathan Feinberg admonishes me that ScheduledExecutorService
is made for this kind of thing. I contend that it's not suitable for the high-frequency, high precision requirement of the OP.
I have a link here from someone complaining in a Sun forum about accuracy problems using this technique: His repeat rate is only 200 ms and yet he's experiencing delays of over 1 second!
Problem with the Java way of doing this is that it's using the operating system's facilities for doing this in a mostly cross-platform manner, and in a way that won't negatively impact the rest of the system. These are compromises; when you have a priority on getting a lot of events out fast and accurately, and you have some leeway on the constraints, it is possible to construct a solution that works better. This is exactly what I've outlined.