Once a timer is running it is possible to subsequently cancel the timer in order to prevent it issuing its timeable callback. This may be illustrated by using timer cancellation to prevent the erroneous callback in Listing 3.3 from triggering and therefore generating an exception. Listing 3.4 shows the changes required. The full code for this example is included in the timer examples package as OneShotTimerExample2.
In Listing 3.4 a reference to the timeable callback object is passed to the cancelTimer method. There is a one-to-one mapping between timers and timeable callback objects which means that the reference to the timeable object can be used to select the timer for cancellation. Note that this means that it is not possible to attach multiple callbacks to a single timer.
Timer cancellation is particularly useful for implementing the timeout idiom. In many applications there are long running tasks where a failure to complete the task within a specified time constitutes an error. An example might be a request from a remote database which if not serviced within a given time implies that the remote database server is inaccessible. This works by requesting a timer callback on issuing the remote request and cancelling it on receiving a response. In the event that a callback to the timeable callback object is actually issued this will be interpreted as a timeout error.