LiveScribe penlet timers

This is a quick post on timers in a LiveScribe pen penlet (pen application). I had asked in the forums about how to track the pen position as it moved across the page. The following is my take on the response I got.

What the above code does is create a new Timer instance when the pen goes down. It also creates a new class that is called when the timer expires. You can used a non-static inner class giving it full access to the parent penlet class, although you might prefer to use a separate class and pass all the required information across in the constructor.

Timers can issue multiple events, which I have used in this case. The Timer.schedule() method takes the callback class to use, the initial timeout, and the time between subsequent timeouts as arguments.

To get the current pen position, in the timer it asks the stroke storage for the last coordinate. See StrokeStorage.getLastCoord().

The end result is you get told about when each pen move occurs.

Beware however that you may need to use synchroized methods to protect penlet class variables. The Timer class uses a separate thread. Its not uncommon in real code to require a synchronized keyword on all the Penlet methods as soon as Timer instances are introduced in order to make sure that any code triggered by the Timer is thread safe with respect to the main Penlet class. Its too big a job to describe synchronization and thread safety here – its important to understand however if you are going to use Timers safely.